gaps and islands
streaks, sessions and missing days. the row_number subtraction trick, stepped through.
- address
- everything.analytics.gaps_and_islands
- part
- part 4, windows, grouping and recursion
- chapter
- chapter 9 of 11
- reading time
- 8 min
an island is a run of consecutive values (days in a row, ids with no hole), and a gap is what's between two islands. the trick: number the rows with row_number(), and subtract the number from the value. inside an island both go up by one per row, so the difference stays constant. GROUP BY the difference, and each group is an island.
for gaps that aren't "exactly one apart" (sessions with a timeout), flag each row that starts something new with lag(), and number the islands with a running sum of the flags.
the picture
you know how "longest daily streak" sounds like it needs a loop: walk the days, count, reset when you miss one? SQL doesn't loop, and it doesn't have to. the problem has a name, gaps and islands, and an old trick that turns streaks into a GROUP BY.
think of a ruler laid next to a staircase. on the steps that are all there, the ruler and the stairs climb together, so the height minus the ruler mark doesn't change. where a step is missing, the stairs jump and the ruler doesn't, so from there on the difference is bigger. each stretch with one difference is a flight of stairs with no hole: an island.
- 1WITH days AS (
- 2 SELECT DISTINCT occurred_at::date AS day
- 3 FROM events
- 4 WHERE user_id = 54 AND occurred_at < '2026-03-20'
- 5)
- 6SELECT min(day) AS first, max(day) AS last, count(*) AS days
- 7FROM (
- 8 SELECT day,
- 9 row_number() OVER (ORDER BY day) AS rn,
- 10 day - row_number() OVER (ORDER BY day)::int AS grp
- 11 FROM days
- 12) AS numbered
- 13GROUP BY grp
- 14ORDER BY first;
| daydate |
|---|
| 2026-03-01 |
| 2026-03-02 |
| 2026-03-03 |
| 2026-03-05 |
| 2026-03-06 |
| 2026-03-07 |
| 2026-03-10 |
| 2026-03-11 |
| 2026-03-12 |
| 2026-03-15 |
| 2026-03-18 |
user 54 was active on 11 of the first 19 days of march. the dashed days have no row at all, and nothing below can see them directly.
the difference itself is meaningless as a date. it's a label. any value works as a label as long as it's the same within an island and different between islands, and "value minus position" is exactly that.
the query
as one query, numbered in a subquery and grouped outside (a window function can't be nested inside GROUP BY's aggregates, and it can't go in WHERE either, window functions has why):
WITH days AS (
SELECT DISTINCT occurred_at::date AS day
FROM events
WHERE user_id = 54 AND occurred_at < '2026-03-20'
)
SELECT min(day) AS first, max(day) AS last, count(*) AS days
FROM (
SELECT day,
day - row_number() OVER (ORDER BY day)::int AS grp
FROM days
) AS numbered
GROUP BY grp
ORDER BY first;| firstdate | lastdate | daysint8 |
|---|---|---|
| 2026-03-01 | 2026-03-03 | 3 |
| 2026-03-05 | 2026-03-07 | 3 |
| 2026-03-10 | 2026-03-12 | 3 |
| 2026-03-15 | 2026-03-15 | 1 |
| 2026-03-18 | 2026-03-18 | 1 |
three things make it work, and each one is a way to break it:
- DISTINCT first. a user with two events on one day has two rows for that day, the numbers run ahead of the days, and an island splits in two. the trick needs one row per value.
::int.row_number()is a bigint, anddate - bigintdoesn't exist;date - intgives a date.- the same ORDER BY as the thing you're measuring: number the days in day order, or the differences are noise.
SELECT count(DISTINCT grp)
FROM (SELECT v - row_number() OVER (ORDER BY v) AS grp
FROM unnest(ARRAY[1, 2, 3, 5, 6, 9, 10]) AS v) AS t;SELECT v, row_number() OVER (ORDER BY v) AS rn, v - row_number() OVER (ORDER BY v) AS grp
FROM unnest(ARRAY[1, 2, 3, 5, 6, 9, 10]) AS v
ORDER BY v;| vint4 | rnint8 | grpint8 |
|---|---|---|
| 1 | 1 | 0 |
| 2 | 2 | 0 |
| 3 | 3 | 0 |
| 5 | 4 | 1 |
| 6 | 5 | 1 |
| 9 | 6 | 3 |
| 10 | 7 | 3 |
the longest streak
partition by user, and every user's days get their own numbering, so one query finds every streak of every user. sort by length:
WITH days AS (SELECT DISTINCT user_id, occurred_at::date AS day FROM events),
islands AS (
SELECT user_id, day,
day - row_number() OVER (PARTITION BY user_id ORDER BY day)::int AS grp
FROM days
)
SELECT user_id, min(day) AS first, max(day) AS last, count(*) AS days
FROM islands
GROUP BY user_id, grp
ORDER BY days DESC, user_id
LIMIT 6;| user_idint4 | firstdate | lastdate | daysint8 |
|---|---|---|---|
| 1 | 2026-04-15 | 2026-05-31 | 47 |
| 2 | 2026-04-15 | 2026-05-31 | 47 |
| 3 | 2026-04-15 | 2026-05-31 | 47 |
| 5 | 2026-04-15 | 2026-05-31 | 47 |
| 1 | 2026-03-01 | 2026-04-13 | 44 |
| 2 | 2026-03-01 | 2026-04-13 | 44 |
nobody beats 47 days, because nobody was active on the 14th. that's the gap side of the problem, and the same subtraction finds it. user 17 has a famous streak in this dataset, 30 days with one day missed; ask for the islands and the miss appears as the space between them:
WITH days AS (SELECT DISTINCT occurred_at::date AS day FROM events WHERE user_id = 17),
islands AS (
SELECT min(day) AS first, max(day) AS last
FROM (SELECT day, day - row_number() OVER (ORDER BY day)::int AS grp FROM days) AS d
GROUP BY grp
)
SELECT last + 1 AS gap_from,
lead(first) OVER (ORDER BY first) - 1 AS gap_to
FROM islands
ORDER BY first;| gap_fromdate | gap_todate |
|---|---|
| 2026-05-05 | 2026-05-05 |
| 2026-05-21 | null |
one gap, 2026-05-05 to 2026-05-05: the missed day. the second row is the streak's end on the 20th; there's no island after it, so gap_to is NULL. (for gaps across the whole calendar, not between someone's islands, a generate_series calendar with a LEFT JOIN is often clearer.)
islands with a timeout: sessions
the subtraction needs values that are exactly one apart inside an island. web sessions aren't like that: "a session ends after 30 minutes of nothing" means any gap under 30 minutes keeps you in it. a different trick, two windows:
lag()gives each event's gap since the previous one (the previous row).- a row starts a new session if the gap is over the timeout (or there's no previous row). flag it 1, else 0.
- a running
sum()of the flags numbers the sessions: it goes up by one at every start.
windows can't be nested, so steps 1 and 2 go in a subquery:
- 1SELECT id, at, kind, gap,
- 2 sum(new) OVER (ORDER BY at, id) AS session
- 3FROM (
- 4 SELECT id, occurred_at::time AS at, kind,
- 5 occurred_at - lag(occurred_at) OVER w AS gap,
- 6 CASE WHEN occurred_at - lag(occurred_at) OVER w <= interval '30 minutes'
- 7 THEN 0 ELSE 1 END AS new
- 8 FROM events
- 9 WHERE user_id = 1 AND occurred_at >= '2026-03-02' AND occurred_at < '2026-03-03'
- 10 WINDOW w AS (ORDER BY occurred_at, id)
- 11) AS flagged
- 12ORDER BY at, id;
| idint8 | attime | kindtext | gapinterval | sessionint8 |
|---|---|---|---|---|
| 279 | 00:20:04 | view | null | 1 |
| 283 | 00:40:05 | view | 00:20:01 | 1 |
| 331 | 04:54:32 | add_to_cart | 04:14:27 | 2 |
| 340 | 05:37:20 | purchase | 00:42:48 | 3 |
| 342 | 05:48:49 | view | 00:11:29 | 3 |
| 407 | 11:30:34 | click | 05:41:45 | 4 |
| 424 | 12:59:57 | view | 01:29:23 | 5 |
| 450 | 15:17:23 | view | 02:17:26 | 6 |
| 467 | 16:44:45 | add_to_cart | 01:27:22 | 7 |
| 475 | 17:25:28 | view | 00:40:43 | 8 |
| 491 | 18:53:16 | add_to_cart | 01:27:48 | 9 |
| 507 | 20:12:16 | view | 01:19:00 | 10 |
| 511 | 20:34:17 | click | 00:22:01 | 10 |
| 537 | 22:52:35 | view | 02:18:18 | 11 |
a new session starts whenever the gap since the previous event is over 30 minutes. a running sum of those starts numbers the sessions: 11 of them.
try the one-step version and postgres tells you why it's two steps:
SELECT id,
sum(CASE WHEN occurred_at - lag(occurred_at) OVER w <= interval '30 minutes'
THEN 0 ELSE 1 END) OVER w AS session
FROM events
WHERE user_id = 1
WINDOW w AS (ORDER BY occurred_at, id);this "flag the starts, then running-sum" pattern is the general one. the subtraction trick is the special case for values that step by exactly one, and it's shorter there, so it's worth knowing both.
keylines
- an island is a run of consecutive values. value minus row_number is constant inside one.
- one row per value first (DISTINCT), and number in the same order you measure.
- GROUP BY the difference: one group per island, with min, max and count.
- for timeouts, flag the rows that start something (lag), then running-sum the flags.
- window functions can't be nested: compute the flag in a subquery.