Gaps and islands
"Find each user's login streaks" and "how long was each rider online without a break" are the same puzzle: find runs of consecutive rows. It is called gaps and islands, and it is one of the most asked hard SQL questions. This lesson solves it with two tricks you can reuse anywhere.
Foundations · SQL for data engineers · Gold · Interview patterns, lesson 1 of 3
On this page
Read first: Window functions: ranking and top N · Running totals and window frames (skip if you know them)
In plain words first
Write Asha's login days on a number line: 1, 2, 3, then 5, 6, then 9 March. The days she logged in form little groups with holes between them:
Islands
Gaps
The hard part is that SQL has no "consecutive" keyword. You need a value that is the same for every row of one island and different between islands. Once you have it, GROUP BY that value gives one row per streak.
The trick: date minus row number
Number each user's logins in date order: 1, 2, 3, ... Along a streak, the date goes up by one day and the row number goes up by one, so date minus row number stays the same. When a day is skipped, the date jumps by more than the row number, and the difference changes.
Input: app_logins
| user_id | login_day |
|---|---|
| asha | 2026-03-01 |
| asha | 2026-03-02 |
| asha | 2026-03-03 |
| asha | 2026-03-05 |
| asha | 2026-03-06 |
| asha | 2026-03-09 |
| ravi | 2026-03-01 |
| ravi | 2026-03-03 |
| ravi | 2026-03-04 |
| ravi | 2026-03-05 |
| ravi | 2026-03-06 |
| meera | 2026-03-02 |
| meera | 2026-03-02 |
| meera | 2026-03-03 |
SELECT user_id, login_day, row_number() OVER (PARTITION BY user_id ORDER BY login_day) AS rn, date_sub( login_day, row_number() OVER (PARTITION BY user_id ORDER BY login_day) ) AS island FROM app_logins WHERE user_id = 'asha' ORDER BY login_day
| login_day | rn | date − rn | Island |
|---|---|---|---|
| 03-01 | 1 | 02-28 | first |
| 03-02 | 2 | 02-28 | first |
| 03-03 | 3 | 02-28 | first |
| 03-05 | 4 | 03-01 | second |
| 03-06 | 5 | 03-01 | second |
| 03-09 | 6 | 03-03 | third |
The island value itself means nothing (28 February is not a login day). It is only a label that the rows of one streak share. Now group by it:
Input: app_logins
| user_id | login_day |
|---|---|
| asha | 2026-03-01 |
| asha | 2026-03-02 |
| asha | 2026-03-03 |
| asha | 2026-03-05 |
| asha | 2026-03-06 |
| asha | 2026-03-09 |
| ravi | 2026-03-01 |
| ravi | 2026-03-03 |
| ravi | 2026-03-04 |
| ravi | 2026-03-05 |
| ravi | 2026-03-06 |
| meera | 2026-03-02 |
| meera | 2026-03-02 |
| meera | 2026-03-03 |
WITH numbered AS ( SELECT user_id, login_day, date_sub( login_day, row_number() OVER (PARTITION BY user_id ORDER BY login_day) ) AS island FROM (SELECT DISTINCT user_id, login_day FROM app_logins) ) SELECT user_id, min(login_day) AS streak_start, max(login_day) AS streak_end, count(*) AS days FROM numbered GROUP BY user_id, island ORDER BY user_id, streak_start
From here, every streak question is one more step: the longest streak is max(days) per user; "users with a streak of 3 days or more" is HAVING count(*) >= 3.
Duplicates break it
The query above reads from SELECT DISTINCT user_id, login_day, not straight from logins. That is not decoration. Meera's login on 2 March is recorded twice. Without DISTINCT, the second copy gets the next row number while the date stays the same, so it lands in a different island:
Input: app_logins
| user_id | login_day |
|---|---|
| asha | 2026-03-01 |
| asha | 2026-03-02 |
| asha | 2026-03-03 |
| asha | 2026-03-05 |
| asha | 2026-03-06 |
| asha | 2026-03-09 |
| ravi | 2026-03-01 |
| ravi | 2026-03-03 |
| ravi | 2026-03-04 |
| ravi | 2026-03-05 |
| ravi | 2026-03-06 |
| meera | 2026-03-02 |
| meera | 2026-03-02 |
| meera | 2026-03-03 |
SELECT user_id, login_day, date_sub( login_day, row_number() OVER (PARTITION BY user_id ORDER BY login_day) ) AS island FROM app_logins WHERE user_id = 'meera'
Two different island values for one two-day streak. Fix it in either of two ways: remove duplicates first (as above), or number with dense_rank() instead of row_number(), which gives both copies the same number. With DENSE_RANK, count days with count(DISTINCT login_day), because the duplicate row is still there.
to_date(login_ts)) and remove duplicates: two logins on one day are one day of the streak. For numbers instead of dates (ticket ids, hours), the same trick is id - row_number().Finding the gaps instead
Sometimes the question is about the holes: when did each user stop, and for how long? LAG answers it directly: compare each day with the previous login and keep the jumps bigger than one day.
Input: app_logins
| user_id | login_day |
|---|---|
| asha | 2026-03-01 |
| asha | 2026-03-02 |
| asha | 2026-03-03 |
| asha | 2026-03-05 |
| asha | 2026-03-06 |
| asha | 2026-03-09 |
| ravi | 2026-03-01 |
| ravi | 2026-03-03 |
| ravi | 2026-03-04 |
| ravi | 2026-03-05 |
| ravi | 2026-03-06 |
| meera | 2026-03-02 |
| meera | 2026-03-02 |
| meera | 2026-03-03 |
WITH days AS ( SELECT DISTINCT user_id, login_day FROM app_logins ), with_prev AS ( SELECT user_id, login_day, lag(login_day) OVER (PARTITION BY user_id ORDER BY login_day) AS prev FROM days ) SELECT user_id, prev AS last_before_gap, login_day AS back_on, datediff(login_day, prev) - 1 AS days_missed FROM with_prev WHERE datediff(login_day, prev) > 1 ORDER BY user_id, login_day
Runs of the same value
The second kind of island is a run of rows with the same value, such as a rider's status checked every hour: online, online, break, online, online, online. Here the rows are already consecutive, so date minus row number does not help. Three steps do:
- 1Flag each row that starts a new run: 1 if its status differs from the previous row's (or there is no previous row), else 0.
- 2Take a running sum of the flags. It goes up by one at each new run, so it numbers the runs: 1, 1, 2, 3, 3, 3.
- 3Group by that run number.
Input: rider_status
| rider | hour | status |
|---|---|---|
| kiran | 9 | online |
| kiran | 10 | online |
| kiran | 11 | break |
| kiran | 12 | online |
| kiran | 13 | online |
| kiran | 14 | online |
| arun | 9 | break |
| arun | 10 | online |
| arun | 11 | online |
SELECT rider, hour, status, CASE WHEN status = lag(status) OVER (PARTITION BY rider ORDER BY hour) THEN 0 ELSE 1 END AS is_new FROM rider_status ORDER BY rider, hour
The first row of each rider has no previous status, so the comparison is NULLNULL: A missing or unknown value. It is not 0 or an empty string, and any comparison with it is unknown instead of true or false. Learn more →, CASE falls through to ELSE, and the row is correctly flagged as a new run.
Input: rider_status
| rider | hour | status |
|---|---|---|
| kiran | 9 | online |
| kiran | 10 | online |
| kiran | 11 | break |
| kiran | 12 | online |
| kiran | 13 | online |
| kiran | 14 | online |
| arun | 9 | break |
| arun | 10 | online |
| arun | 11 | online |
WITH flagged AS ( SELECT rider, hour, status, CASE WHEN status = lag(status) OVER (PARTITION BY rider ORDER BY hour) THEN 0 ELSE 1 END AS is_new FROM rider_status ), numbered AS ( SELECT *, sum(is_new) OVER (PARTITION BY rider ORDER BY hour) AS run_id FROM flagged ) SELECT rider, status, min(hour) AS from_hour, max(hour) + 1 AS to_hour, count(*) AS hours FROM numbered GROUP BY rider, status, run_id ORDER BY rider, from_hour
Kiran was online from 9 to 11, on a break for an hour, then online from 12 to 15. This flag-and-sum pattern works for any "consecutive rows with the same something": the same status, price, plan or error code. It is also the basis of sessionization, the next lesson.
Common mistakes
- Running the trick on duplicate rows — A repeated day gets its own row number and splits the streak. Use SELECT DISTINCT first, or dense_rank.
- Forgetting PARTITION BY user — Row numbers run across users, so one user's streak is measured against another's days. Partition by the entity whose streaks you want.
- Using date minus row number for runs of a value — It only finds consecutive dates or numbers. For runs of the same status, flag changes with LAG and take a running sum.
- Treating the island key as a real date — It is only a label shared by the rows of one streak. Report min and max of the real dates instead.
Key takeaways
- An island is a run of consecutive rows; a gap is the hole between two islands.
- Consecutive dates: date minus row_number is constant within an island; group by it.
- Remove duplicates first, or use dense_rank, or streaks split.
- Runs of the same value: flag changes with LAG, running-sum the flags, group by the sum.
- Gaps: LAG to the previous row and keep jumps bigger than one step.
Interview prep
THE QUESTION
"Find users who logged in on at least 3 consecutive days."
row_number() OVER (PARTITION BY user_id ORDER BY login_day), and subtract that number of days from the date: the result is constant within a streak. Group by user and that key, keep groups with count(*) >= 3, and select the distinct users. Then mention the traps: duplicates split streaks (hence DISTINCT, or DENSE_RANK), and timestamps must be truncated to dates first. An alternative is lag(login_day, 2): if it is exactly two days before the current date (on de-duplicated days), the user has a 3-day run ending today.Avoid: A self join for each consecutive day (d, d + 1, d + 2). It answers "3 days" but not "4 days" or "the longest streak" without rewriting, and it grows badly. The window trick handles any length in one pass.
Follow-ups · answer out loud, then open
Follow-up"Return each user's longest streak."
max(days) per user in one more step. If the streak dates are needed too, rank the streaks per user by length with ROW_NUMBER and keep rank 1, with a tie-breaker such as the start date.Scenario"Login events are timestamps in UTC, and some users log in several times a day."
Trap"Can you use date minus row number to find runs of the same order status?"
Check yourself
4 questionsLogins on 5, 6 and 7 March get row numbers 1, 2, 3. What is date minus row number?
Show the answer
4, 4, 4 March. 5 − 1, 6 − 2 and 7 − 3 are all 4 March: one island.
A user has two rows for 6 March. What happens with row_number and no DISTINCT?
Show the answer
The streak is split into two islands. The second copy gets the next number but the same date, so its key differs.
Status values A, A, B, A. After flagging changes and a running sum, what are the run ids?
Show the answer
1, 1, 2, 3. Flags are 1, 0, 1, 1; their running sum is 1, 1, 2, 3.
Which pattern fits "hours a rider spent online without a break"?
Show the answer
Flag changes and running sum. It is a run of the same value, not a run of consecutive dates.
Practise this
Problems that use this, graded on hidden tests
Keep going
Up next · Interview patterns · lesson 2 of 3 · 7 min readSessionization
Split a clickstream into sessions with an inactivity timeout, then measure each session.
Related lessons
Running totals and window framesSQL for data engineers · 6 min read
LAG and LEAD
Previous: Dates and date spines
Primary sources: Window functions · Date functions (date_sub, datediff)