Find users with three or more consecutive login days
A logins(user_id, login_at) table has one row per login, and a user can log in several times a day. Return each user who logged in on at least three consecutive calendar days, with the start and end of their longest streak.
Think it through or sketch an answer first, then open the hint or the solution.
Show a hint
Deduplicate to one row per user per day first. Then subtract a row number from the date: consecutive days share the same result.
Show the solution
This is the gaps-and-islands pattern. After reducing to distinct days, number each user's days in order. For consecutive days, day - row_number is constant, so it identifies each island. Group by that key to get streak lengths and keep the ones of three days or more.
Example (SQL)
WITH days AS (
SELECT DISTINCT user_id, DATE(login_at) AS d FROM logins
), grp AS (
SELECT user_id, d,
DATE(d, '-' || ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY d) || ' days') AS island
FROM days
)
SELECT user_id, MIN(d) AS streak_start, MAX(d) AS streak_end, COUNT(*) AS days
FROM grp
GROUP BY user_id, island
HAVING COUNT(*) >= 3;
-- SQLite date arithmetic; in other engines use d - ROW_NUMBER() * INTERVAL '1 day'
Common mistakes
- Skipping the per-day deduplication: two logins on one day break the date-minus-row-number arithmetic.
- Using LAG() to compare only with the previous row: it finds pairs, not runs of three or more.
How did you do? Your answer is saved in this browser and comes back for revision later.