Advanced
Open
Pro
Longest Consecutive Active-Day Streak Per User
Given a table of the distinct days each user was active:
daily_activity
user_id | activity_date
--------+---------------
1 | 2026-08-01
1 | 2026-08-02
1 | 2026-08-03
1 | 2026-08-05 -- gap: no activity on 08-04
1 | 2026-08-06
2 | 2026-08-01
2 | 2026-08-02
Find each user's longest streak of consecutive active days, and the start/end date of that streak. For user 1, the answer should be a 3-day streak (Aug 1–3), not 5 days — the Aug 4 gap breaks it, even though Aug 5–6 continues immediately after.
Write the full query and explain the "gaps and islands" trick your solution relies on — specifically, why subtracting a row number from the date produces a constant value for every row inside one unbroken streak.
Share this question