skip to content

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.

islands.sqlstep 1
  1. 1WITH days AS (
  2. 2 SELECT DISTINCT occurred_at::date AS day
  3. 3 FROM events
  4. 4 WHERE user_id = 54 AND occurred_at < '2026-03-20'
  5. 5)
  6. 6SELECT min(day) AS first, max(day) AS last, count(*) AS days
  7. 7FROM (
  8. 8 SELECT day,
  9. 9 row_number() OVER (ORDER BY day) AS rn,
  10. 10 day - row_number() OVER (ORDER BY day)::int AS grp
  11. 11 FROM days
  12. 12) AS numbered
  13. 13GROUP BY grp
  14. 14ORDER BY first;
the active days
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
(11 rows)

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.

step 1/4
real output, postgres 18.6 (PGlite 0.5.12) · gaps-and-islands
user 54's first nineteen days. step through: number the active days, subtract, group. after step 3, every day of an island shows the same difference, and the difference only moves at a gap (dashed: no row that day).

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):

sqldb=events
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;
output, from postgres 18.6
SELECT 5
firstdatelastdatedaysint8
2026-03-012026-03-033
2026-03-052026-03-073
2026-03-102026-03-123
2026-03-152026-03-151
2026-03-182026-03-181
(5 rows)

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, and date - bigint doesn't exist; date - int gives a date.
  • the same ORDER BY as the thing you're measuring: number the days in day order, or the differences are noise.
predict the output
sql
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;
sqlempty db
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;
output, from postgres 18.6
SELECT 7
vint4rnint8grpint8
110
220
330
541
651
963
1073
(7 rows)

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:

user 1, 04-15 to 05-3147 days
user 2, 04-15 to 05-3147 days
user 3, 04-15 to 05-3147 days
user 5, 04-15 to 05-3147 days
user 1, 03-01 to 04-1344 days
user 2, 03-01 to 04-1344 days
the six longest streaks in the events table, from the query below. every top streak starts on april 15 or ends on april 13: 2026-04-14 has no events at all, so it cuts every user's streak in two.
sqldb=events
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;
output, from postgres 18.6
SELECT 6
user_idint4firstdatelastdatedaysint8
12026-04-152026-05-3147
22026-04-152026-05-3147
32026-04-152026-05-3147
52026-04-152026-05-3147
12026-03-012026-04-1344
22026-03-012026-04-1344
(6 rows)

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:

sqldb=events
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;
output, from postgres 18.6
SELECT 2
gap_fromdategap_todate
2026-05-052026-05-05
2026-05-21null
(2 rows)

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:

  1. lag() gives each event's gap since the previous one (the previous row).
  2. a row starts a new session if the gap is over the timeout (or there's no previous row). flag it 1, else 0.
  3. 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:

timeout =
query.sql
  1. 1SELECT id, at, kind, gap,
  2. 2 sum(new) OVER (ORDER BY at, id) AS session
  3. 3FROM (
  4. 4 SELECT id, occurred_at::time AS at, kind,
  5. 5 occurred_at - lag(occurred_at) OVER w AS gap,
  6. 6 CASE WHEN occurred_at - lag(occurred_at) OVER w <= interval '30 minutes'
  7. 7 THEN 0 ELSE 1 END AS new
  8. 8 FROM events
  9. 9 WHERE user_id = 1 AND occurred_at >= '2026-03-02' AND occurred_at < '2026-03-03'
  10. 10 WINDOW w AS (ORDER BY occurred_at, id)
  11. 11) AS flagged
  12. 12ORDER BY at, id;
the result for 30 minutes
idint8attimekindtextgapintervalsessionint8
27900:20:04viewnull1
28300:40:05view00:20:011
33104:54:32add_to_cart04:14:272
34005:37:20purchase00:42:483
34205:48:49view00:11:293
40711:30:34click05:41:454
42412:59:57view01:29:235
45015:17:23view02:17:266
46716:44:45add_to_cart01:27:227
47517:25:28view00:40:438
49118:53:16add_to_cart01:27:489
50720:12:16view01:19:0010
51120:34:17click00:22:0110
53722:52:35view02:18:1811
(14 rows)

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.

real output, postgres 18.6 (PGlite 0.5.12) · gaps-and-islands
user 1's fourteen events on 2 march 2026. switch the timeout: at 30 minutes the day is 11 sessions, at 90 minutes it's 5. the shaded runs are the sessions, numbered by the running sum.

try the one-step version and postgres tells you why it's two steps:

sqldb=events
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);
output, from postgres 18.6
ERROR 42P20: window function calls cannot be nested
2 │ sum(CASE WHEN occurred_at - lag(occurred_at) OVER w <= interval '30 minutes'
at line 2, column 36

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.