Query to find streaks
WITH days AS (
SELECT DISTINCT user, day
FROM activity_streaks_demo
WHERE day IS NOT NULL
), previous AS (
SELECT user, day,
LAG(day) OVER (PARTITION BY user ORDER BY day) AS previous
FROM days
), marks AS (
SELECT user, day,
CASE WHEN day = DATE(previous, '+1 day')
THEN 0 ELSE 1 END AS new_streak
FROM previous
), groups AS (
SELECT user, day,
SUM(new_streak) OVER (
PARTITION BY user ORDER BY day
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS group_label
FROM marks
)
SELECT user, MIN(day) AS start, MAX(day) AS end,
COUNT(*) AS consecutive_days
FROM groups
GROUP BY user, group_label
ORDER BY user, start;Set up the example data
Amy is active on 28 and 29 February and 1 March, and comes back on the 3rd and 4th. Liam is not active on the leap day, so his 28 February is separated from 1 March. Amy's repeated 28 February and Liam's repeated 7 March must not lengthen the streaks.
The TEXT in the example contains only valid, consistently formatted YYYY-MM-DD dates with no times. The application must enforce that rule when data is entered. In PostgreSQL, MySQL or SQL Server, a DATE column expresses this case better.
CREATE TABLE activity_streaks_demo (
id INTEGER PRIMARY KEY,
user TEXT NOT NULL,
day TEXT
);
INSERT INTO activity_streaks_demo VALUES
(1, 'Amy', '2024-02-28'),
(2, 'Amy', '2024-02-28'),
(3, 'Amy', '2024-02-29'),
(4, 'Amy', '2024-03-01'),
(5, 'Amy', '2024-03-03'),
(6, 'Amy', '2024-03-04'),
(7, 'Amy', NULL),
(8, 'Liam', '2024-02-28'),
(9, 'Liam', '2024-03-01'),
(10, 'Liam', '2024-03-02'),
(11, 'Liam', '2024-03-03'),
(12, 'Liam', '2024-03-07'),
(13, 'Liam', '2024-03-07');Download the full example (.sql)
The download uses an empty SQLite database with the same data and queries as this guide. Run it once on a test connection. The course's teaching editor has a limited engine, so run this script in SQLite rather than in the course lab.
Verified streaks per user
| user | start | end | consecutive_days |
|---|---|---|---|
| Amy | 2024-02-28 | 2024-03-01 | 3 |
| Amy | 2024-03-03 | 2024-03-04 | 2 |
| Liam | 2024-02-28 | 2024-02-28 | 1 |
| Liam | 2024-03-01 | 2024-03-03 | 3 |
| Liam | 2024-03-07 | 2024-03-07 | 1 |
The thirteen starting rows represent ten distinct known days across the two users, and the streak lengths in the result add up to ten. Checking that total helps you spot a repeat you forgot to remove, or different users grouped together by mistake.
How it works
What “consecutive” means in this report
We count calendar days, not 24-hour periods or working days. 28 February and 1 March 2024 are not consecutive: the 29th falls between them, because 2024 is a leap year. A change of month or year does not break a sequence by itself.
If the source includes times, first convert each event to the business day in the agreed time zone, and only then remove repeated days. Truncating a UTC timestamp to a date can put an event on the wrong day for the user, and adding 86,400 seconds does not always land on the next local day when the clocks change.
Streak rules in this guide
| Scenario | Decision |
|---|---|
| Several activities by the same user on the same day | Count as a single daily presence |
| A NULL date | Excluded; it does not represent a known day |
| A different user | A separate sequence |
| A day with no activity | A new streak starts when they come back |
| Weekends and holidays | Counted like any other calendar day |
Why the four stages work
1. days: fix the unit we are counting
SELECT DISTINCT user, day reduces events to daily attendance. Each attendance record includes the user; DISTINCT day without user would mix different people. Excluding NULL before LAG avoids treating an unknown date as a step in the sequence.
2. previous: compare within each user
LAG(day) returns the previous day in the given order. PARTITION BY user restarts that comparison for each person. The first row has no predecessor and gets NULL. The window's ORDER BY defines the comparison; the one in the final SELECT defines how the report is displayed.
3. marks: decide when a new streak starts
DATE(previous, '+1 day') calculates the next calendar day. If it equals day, the flag is zero; otherwise it is one. For the first row, the comparison with NULL is not true, so ELSE correctly starts the first streak.
Amy's intermediate flags
| day | previous day | new_streak |
|---|---|---|
| 2024-02-28 | NULL | 1 |
| 2024-02-29 | 2024-02-28 | 0 |
| 2024-03-01 | 2024-02-29 | 0 |
| 2024-03-03 | 2024-03-01 | 1 |
| 2024-03-04 | 2024-03-03 | 0 |
4. groups: accumulate the starts and summarise
The running sum of flags is one for Amy's first sequence and two for the next. The explicit ROWS frame accumulates from the start of the partition up to the current row. Dates are unique per user at this stage, because days has already removed the repeats.
GROUP BY user, group_label brings together the rows that share a streak. MIN and MAX give its boundaries; COUNT counts days, not the number of original events. The CTEs separate window calculations that cannot be nested directly inside another window at the same level.
Cases that change the result
Mistakes that change the answer
Counting events instead of days
If you skip days, the second activity on 28 February comes right after another on the same day. It is not the next day, so it can start a false streak. Removing duplicates at the end does not repair groups that were already built wrongly.
Using the id as a measure of time
The id identifies events; it does not guarantee continuous dates or that events arrived in chronological order. A record imported late can have a high id and an old date. Sort by the day the report is about, not by a technical insertion sequence.
Filtering the period before deciding what you need to measure
Filtering dates before LAG answers “streaks within this period” and can cut off a sequence that started earlier. If you need the full length of the streaks that overlap March, compute the streaks over the whole history first and then keep those where start < '2024-04-01' AND end >= '2024-03-01'. Amy's streak will keep its February start and its three days.
For a very long history, widening the window by a few days does not guarantee finding the true start of a long streak. Decide whether the product needs the full history, an observation limit or incremental state, and show that limitation in the report.
Confusing working days with calendar days
If Friday and Monday should count as consecutive, DATE(previous, '+1 day') does not implement that rule. Use a business calendar with a consecutive position for each valid day, and compare positions. Also document whether activity on a public holiday counts or is discarded. The flag technique still works, but the meaning of “next” changes.
Next-day comparison by engine
The structure of CTEs, LAG and SUM with OVER carries over to modern engines. What changes is the calendar expression and the type of day. This table assumes day and previous are of type DATE on the other three engines:
Expression that signals continuity
| Engine | Condition for not starting a new streak |
|---|---|
| SQLite, validated ISO text | day = DATE(previous, '+1 day') |
| PostgreSQL, DATE | day = previous + 1 |
| MySQL 8.0+, DATE | day = DATE_ADD(previous, INTERVAL 1 DAY) |
| SQL Server, DATE | day = DATEADD(day, 1, previous) |
Date arithmetic is documented in PostgreSQL (opens in a new tab), MySQL (opens in a new tab) and SQL Server (opens in a new tab). For a column with times, first reshape the model into daily presences; do not just change the function name.
An index on (user, day) can help read the history and sort the presences, but DISTINCT and the analytic stages may need extra work. Check the plan and the cost at real data volumes; having the index does not guarantee every sort disappears.
CREATE INDEX ix_activity_streaks_user_day
ON activity_streaks_demo(user, day);Finding the longest streak
WITH days AS (
SELECT DISTINCT user, day
FROM activity_streaks_demo
WHERE day IS NOT NULL
), previous AS (
SELECT user, day,
LAG(day) OVER (PARTITION BY user ORDER BY day) AS previous
FROM days
), marks AS (
SELECT user, day,
CASE WHEN day = DATE(previous, '+1 day')
THEN 0 ELSE 1 END AS new_streak
FROM previous
), groups AS (
SELECT user, day,
SUM(new_streak) OVER (
PARTITION BY user ORDER BY day
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS group_label
FROM marks
), streaks AS (
SELECT user, MIN(day) AS start, MAX(day) AS end,
COUNT(*) AS consecutive_days
FROM groups
GROUP BY user, group_label
), ranking AS (
SELECT user, start, end, consecutive_days,
ROW_NUMBER() OVER (
PARTITION BY user
ORDER BY consecutive_days DESC, start ASC
) AS position
FROM streaks
)
SELECT user, start, end, consecutive_days
FROM ranking
WHERE position = 1
ORDER BY user;One winning streak per user
| user | start | end | consecutive_days |
|---|---|---|---|
| Amy | 2024-02-28 | 2024-03-01 | 3 |
| Liam | 2024-03-01 | 2024-03-03 | 3 |
ROW_NUMBER is calculated over streaks, so the ordering can use consecutive_days. The tiebreaker on start decides which one is returned when lengths match. To keep every streak tied on length, use a ranking that does not break ties on start.