Part 08 / Topic 7 of 10
Gaps and islands
Consecutive runs ("islands") and the holes between them ("gaps") — login streaks, outage windows, missing invoice numbers. The classic trick: for consecutive values, value - ROW_NUMBER() is constant — so it identifies each island:
WITH logins AS (
SELECT * FROM (VALUES
(DATE '2025-05-01'), (DATE '2025-05-02'), (DATE '2025-05-03'),
(DATE '2025-05-06'),
(DATE '2025-05-08'), (DATE '2025-05-09')
) AS t(login_date)
),
marked AS (
SELECT login_date,
login_date - (ROW_NUMBER() OVER (ORDER BY login_date))::int AS island
FROM logins
)
SELECT min(login_date) AS streak_start,
max(login_date) AS streak_end,
count(*) AS days
FROM marked
GROUP BY island
ORDER BY streak_start;
streak_start | streak_end | days
--------------+------------+------
2025-05-01 | 2025-05-03 | 3
2025-05-06 | 2025-05-06 | 1
2025-05-08 | 2025-05-09 | 2
(3 rows)
Walk it: May 1/2/3 minus row numbers 1/2/3 all give April 30 — one island. The jump to May 6 breaks the arithmetic, starting a new one. Group by the island key and each streak collapses to a row. It feels like a magic trick exactly once; after that it's a tool.
🧪 Quick quiz — answer from memory, then check.
- Why is
date - row_number()constant within a streak? - What breaks the constant?
Show the answers
- Both increase by exactly 1 per row while days are consecutive, so their difference stands still.
- A gap — the date jumps by more than the row number does, shifting the difference to a new value.
Done here? The practice set for Part 8 — 8 exercises with solutions — is on the part page.