Identifying Gaps and Islands in Sequential Data
Find contiguous islands and missing gaps in sequences of dates or IDs.
In plain words
Number the rows in order. For a run of back-to-back values, "value minus row number" stays the same, so you can group the run together.
Think of it like…
Numbering the days you went to the gym: if you went on days 3, 4, 5 and your personal visit counter reads 1, 2, 3, the difference is 2 each time. When you skip a day, the dates jump ahead but the counter doesn't, so the difference changes. Each difference value marks one streak.
Where you’ve seen it
Finding each user's longest daily login streak: deduplicate to one row per user per day, compute login_date - ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY login_date) as a group key, then take the largest group per user.
Words you’ll hear
- Island
- A maximal run of consecutive values.
- Gap
- Missing values between two islands.
- Group key
- value − ROW_NUMBER(), constant within each island.
- Deduplication first
- Repeated values break the trick, so reduce to one row per value first.
Visual diagram
Theory & example queries
Finding islands with the ROW_NUMBER trick
Within a run of consecutive integers, both the value and its row number go up by 1 each step, so their difference doesn't change. When the sequence skips, the value jumps by more than 1 while the row number still goes up by 1, so the difference changes and a new island begins.
For dates the same idea works with date arithmetic: login_date - (ROW_NUMBER() OVER (…))::int in PostgreSQL gives the same date for every day in a streak. Then GROUP BY that key and take MIN, MAX and COUNT to describe each island.
WITH d AS ( SELECT DISTINCT user_id, login_at::date AS DAY FROM logins ), g AS ( SELECT user_id, DAY, DAY - ( ROW_NUMBER() OVER ( PARTITION BY user_id ORDER BY DAY ) )::int AS grp FROM d )SELECT user_id, MIN(DAY) AS start_day, MAX(DAY) AS end_day, COUNT(*) AS streakFROM gGROUP BY user_id, grp;PostgreSQL is the lesson baseline unless noted otherwise.
Read this line together with the surrounding statement as part of the same SQL expression.
Representative login streaks3 sample rows
| user_id | start_day | end_day | streak |
|---|---|---|---|
| 7 | 2026-11-01 | 2026-11-03 | 3 |
| 7 | 2026-11-07 | 2026-11-08 | 2 |
| 12 | 2026-10-29 | 2026-10-31 | 3 |
Note: Illustrative results for deduplicated login dates; actual dates, users and streaks come from the logins table.
Key takeaway: Deduplicate, subtract the row number, group by the difference.
Finding gaps, and other variations
Gaps are easier with LEAD: compare each value with the next one, and wherever LEAD(value) - value > 1, there's a gap from value + 1 to the next value − 1. This is how you'd list missing invoice numbers or days with no sales.
When islands are defined by a repeated *status* rather than consecutive numbers (a server's up/down periods), use the difference of two row numbers: ROW_NUMBER() OVER (ORDER BY ts) - ROW_NUMBER() OVER (PARTITION BY status ORDER BY ts) is constant within each run of the same status.
SELECT invoice_no + 1 AS gap_start, next_no - 1 AS gap_endFROM ( SELECT invoice_no, LEAD(invoice_no) OVER ( ORDER BY invoice_no ) AS next_no FROM invoices ) tWHERE next_no - invoice_no > 1;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Representative missing ranges2 sample rows
| gap_start | gap_end |
|---|---|
| 1024 | 1026 |
| 1031 | 1031 |
Note: Assumes consecutive invoice numbers include 1023, 1027, 1030 and 1032 around the gaps.
Key takeaway: LEAD finds gaps; a row-number difference finds islands.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Reduce to one row per value
Remove duplicates (two logins on the same day) with DISTINCT, or the row numbers stop lining up with the values.
SELECT DISTINCT user_id, login_at::dateWhen to use it & trade-offs
What it is
Islands are runs of consecutive values (days a user logged in in a row, unbroken ranges of ids); gaps are the missing values between them. The classic trick: for consecutive values, value − ROW_NUMBER() stays constant within a run, so grouping by that difference turns each island into one group.
Why it matters: Login streaks, uptime periods, consecutive booking dates and missing invoice numbers are all gaps-and-islands problems. It's a well-known advanced SQL interview question, because the ROW_NUMBER trick isn't obvious until you've seen it.
When to reach for it
- Login, purchase or activity streaks
- Uptime and downtime periods from status logs
- Missing ids, invoice numbers or dates
When to avoid or be careful
- Applying the trick to data with duplicate values
- Forgetting PARTITION BY, so different users' days merge into one sequence
- Self-join solutions that compare every row with every other row
Approaches to gaps and islands
Strengths: One pass with window functions, then a GROUP BY.
Watch out: Needs deduplicated input and a little explanation.
Strengths: Flexible; handles any "starts a new run" condition.
Watch out: Two window passes.
Strengths: Shows each gap day as a row.
Watch out: More rows to process.
Interview signals & numbers to know
When this topic comes up
- “Longest streak of consecutive days”
- “Find missing numbers in a sequence”
- “Group consecutive rows with the same status”
- Uptime periods
- Consecutive dates
Benchmarks & rules of thumb
- value − rn
- constant within an island
- LEAD − value > 1
- a gap follows
- 2
- window passes for rule-based islands
Common mistakes & follow-ups
Common interview mistakes
- Skipping DISTINCT, so a user who logged in twice on one day breaks the streak calculation.
- Subtracting ROW_NUMBER from a timestamp instead of a date, so nothing lines up.
- Using RANK or DENSE_RANK instead of ROW_NUMBER without thinking through how ties affect the difference.
Likely interviewer follow-ups
- How would you find each user's longest login streak?
- How would you group consecutive rows with the same status into periods?
- How would you list every missing date between the first and last order?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Identifying Gaps and Islands in Sequential Data with hands-on SQL practice and interview Q&A.