Skip to content
Gold 8 min read · Patterns 2 practice problems ↓

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

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

Runs of consecutive days: 1 to 3 March, 5 to 6 March, and 9 March on its own. Each island is a streak.

Gaps

The missing days between islands: 4 March, and 7 to 8 March.

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.

Spark SQL · Asha's logins with their island key

Input: app_logins

user_idlogin_day
asha2026-03-01
asha2026-03-02
asha2026-03-03
asha2026-03-05
asha2026-03-06
asha2026-03-09
ravi2026-03-01
ravi2026-03-03
ravi2026-03-04
ravi2026-03-05
ravi2026-03-06
meera2026-03-02
meera2026-03-02
meera2026-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_dayrndate − rnIsland
03-01102-28first
03-02202-28first
03-03302-28first
03-05403-01second
03-06503-01second
03-09603-03third

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:

Spark SQL · Every streak of every user

Input: app_logins

user_idlogin_day
asha2026-03-01
asha2026-03-02
asha2026-03-03
asha2026-03-05
asha2026-03-06
asha2026-03-09
ravi2026-03-01
ravi2026-03-03
ravi2026-03-04
ravi2026-03-05
ravi2026-03-06
meera2026-03-02
meera2026-03-02
meera2026-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:

Spark SQL · Meera without DISTINCT: one streak split in two

Input: app_logins

user_idlogin_day
asha2026-03-01
asha2026-03-02
asha2026-03-03
asha2026-03-05
asha2026-03-06
asha2026-03-09
ravi2026-03-01
ravi2026-03-03
ravi2026-03-04
ravi2026-03-05
ravi2026-03-06
meera2026-03-02
meera2026-03-02
meera2026-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.

Tip: With timestamps instead of dates, take the date first (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.

Spark SQL · Every break between logins

Input: app_logins

user_idlogin_day
asha2026-03-01
asha2026-03-02
asha2026-03-03
asha2026-03-05
asha2026-03-06
asha2026-03-09
ravi2026-03-01
ravi2026-03-03
ravi2026-03-04
ravi2026-03-05
ravi2026-03-06
meera2026-03-02
meera2026-03-02
meera2026-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:

  1. 1
    Flag 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.
  2. 2
    Take 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.
  3. 3
    Group by that run number.
Spark SQL · Step 1: flag where a new run starts

Input: rider_status

riderhourstatus
kiran9online
kiran10online
kiran11break
kiran12online
kiran13online
kiran14online
arun9break
arun10online
arun11online
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.

Spark SQL · Steps 2 and 3: number the runs, then group

Input: rider_status

riderhourstatus
kiran9online
kiran10online
kiran11break
kiran12online
kiran13online
kiran14online
arun9break
arun10online
arun11online
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."

Gaps and islands. Remove duplicate logins per day, number each user's days with 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."
Build the streaks as before (group by user and the date-minus-row-number key, count the days), then take 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."
Convert to the business time zone, take the date, and de-duplicate to one row per user and day before numbering. Otherwise a second login on the same day splits the streak, and a late-night login in UTC lands on the wrong day.
Trap"Can you use date minus row number to find runs of the same order status?"
No: that trick needs values that go up by exactly one step (consecutive dates or ids). For runs of an unchanging value, compare each row with LAG to flag where a run starts, then a running sum of the flags numbers the runs.

Check yourself

4 questions

Logins 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 read
Sessionization
Split a clickstream into sessions with an inactivity timeout, then measure each session.

Related lessons

Previous: Dates and date spines

Primary sources: Window functions · Date functions (date_sub, datediff)