Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 78/ 160
04. Subqueries & Common Table Expressions (CTEs)

Identifying Gaps and Islands in Sequential Data

Find contiguous islands and missing gaps in sequences of dates or IDs.

AdvancedGaps · Islands3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Login streaks per user (PostgreSQL)Query example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1WITH2  d AS (3    SELECT DISTINCT4      user_id,5      login_at::date AS DAY6    FROM7      logins8  ),9  g AS (10    SELECT11      user_id,12      DAY,13      DAY - (14        ROW_NUMBER() OVER (15          PARTITION BY16            user_id17          ORDER BY18            DAY19        )20      )::int AS grp21    FROM22      d23  )24SELECT25  user_id,26  MIN(DAY) AS start_day,27  MAX(DAY) AS end_day,28  COUNT(*) AS streak29FROM30  g31GROUP BY32  user_id,33  grp;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/33
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative login streaks3 sample rows
Representative login streaks
user_idstart_dayend_daystreak
72026-11-012026-11-033
72026-11-072026-11-082
122026-10-292026-10-313

Note: Illustrative results for deduplicated login dates; actual dates, users and streaks come from the logins table.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Missing invoice numbersQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  invoice_no + 1 AS gap_start,3  next_no - 1 AS gap_end4FROM5  (6    SELECT7      invoice_no,8      LEAD(invoice_no) OVER (9        ORDER BY10          invoice_no11      ) AS next_no12    FROM13      invoices14  ) t15WHERE16  next_no - invoice_no > 1;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/16
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative missing ranges2 sample rows
Representative missing ranges
gap_startgap_end
10241026
10311031

Note: Assumes consecutive invoice numbers include 1023, 1027, 1030 and 1032 around the gaps.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: LEAD finds gaps; a row-number difference finds islands.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Deduplicate

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.

SQL at this step
1SELECT DISTINCT2  user_id,3  login_at::date
What to watch at this step
Required
one row per value
Tip: use ← → to move between steps

When 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

value − ROW_NUMBER()
Best for: Islands of consecutive numbers or dates

Strengths: One pass with window functions, then a GROUP BY.

Watch out: Needs deduplicated input and a little explanation.

LAG/LEAD + running SUM of "new island" flags
Best for: Islands defined by a rule (gap of more than 30 minutes, status change)

Strengths: Flexible; handles any "starts a new run" condition.

Watch out: Two window passes.

Join to a calendar / generate_series
Best for: Listing every missing date explicitly

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?
Interview tip: Explain the trick with a five-value example (1, 2, 3, 7, 8 → differences 0, 0, 0, 3, 3) before writing SQL. Once the interviewer sees why it works, the query is easy to follow.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Calculating Running Balances & Period-over-Period Growth
Next topic
Sessionization Queries (Grouping User Events by Inactivity Timeout)