Users with a 3-day login streak
Task
logins has one row per user per day they logged in (some days repeat). Return the user_id of every user who logged in on at least 3 consecutive days.
Row order does not matter. Column names do not have to match. SQLite dialect.
Tables
logins
user_id INTEGER, day TEXT
| user_id | day |
|---|---|
| 1 | 2026-05-01 |
| 1 | 2026-05-02 |
| 1 | 2026-05-04 |
| 1 | 2026-05-05 |
| 2 | 2026-05-01 |
| 2 | 2026-05-02 |
| 2 | 2026-05-02 |
| 2 | 2026-05-03 |
| 3 | 2026-05-10 |
| 3 | 2026-05-11 |
| 3 | 2026-05-12 |
| 3 | 2026-05-13 |
| 4 | 2026-05-01 |
| 4 | 2026-05-03 |
| 4 | 2026-05-05 |
- Remove duplicate (user, day) rows first, or the repeated day breaks the pattern.
- Day minus ROW_NUMBER() is constant across a run of consecutive days: group by it and count.
Expected output
| user_id |
|---|
| 2 |
| 3 |
Show solution
WITH d AS (SELECT DISTINCT user_id, day FROM logins),
g AS (
SELECT user_id, day,
julianday(day) - ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY day) AS grp
FROM d
)
SELECT DISTINCT user_id
FROM g
GROUP BY user_id, grp
HAVING COUNT(*) >= 3;Subtracting a row number from consecutive dates gives the same value for every day in a run, so each streak becomes one group. Deduplicate first: user 2's repeated 2 May shifts the row numbers and splits a real 3-day streak. Counting distinct days is not enough either: user 1 and user 4 have 3+ days but no 3 in a row.
Why this works
Subtracting a row number from consecutive dates gives the same value for every day in a run, so each streak becomes one group. Deduplicate first: user 2's repeated 2 May shifts the row numbers and splits a real 3-day streak. Counting distinct days is not enough either: user 1 and user 4 have 3+ days but no 3 in a row.
The full explanation, with more examples, is in the question Users with a 3-day login streak.