Gaps & Islands + Sessionization in SQL
Constant-difference blocks; flag-plus-cumulative sessions
Islands: subtract a row-number sequence from the ordered key — constant differences mark contiguous blocks, GROUP BY the difference. Sessions: LAG timestamps, flag gaps over threshold, cumulative SUM of flags as session ids. Difference-of-sequences is the whiteboard insight; flag-plus-sum is production sessionization for event logs.
Island key
id − ROW_NUMBER() OVER (ORDER BY id) constant per contiguous block.
Group the key
GROUP BY grp with MIN/MAX bounds — gaps vanish into key changes.
Flag time gaps
LAG(ts) per user; flag where gap > threshold (30 min).
Cumulative sessions
SUM(flag) OVER (PARTITION BY user ORDER BY ts) assigns session ids.
1-- island bounds:2SELECT MIN(id) AS start_id, MAX(id) AS end_id FROM (SELECT id, id - ROW_NUMBER() OVER (ORDER BY id) AS grp FROM tickets) t GROUP BY grp;
| start_id | end_id |
|---|---|
| 1 | 3 |
| 7 | 9 |
IDs 1,2,3 share one difference (block one); 7,8,9 share another. Gaps 4-6 vanish into the grouping key. Same LAG+difference toolkit sessionizes clickstreams by time gaps.
Ticket blocks 1-3, 7-9
Two islands from one difference.
1SELECT MIN(id) AS s, MAX(id) AS e FROM (SELECT id, id - ROW_NUMBER() OVER (ORDER BY id) AS grp FROM tickets) t GROUP BY grp;
| start_id | end_id |
|---|---|
| 1 | 3 |
| 7 | 9 |
30-min sessions
Flag + running sum sessionizes.
1-- flag gaps, then:2-- SUM(flag) OVER (PARTITION BY user_id ORDER BY ts) AS session_id
| user_id | sessions |
|---|---|
| user_7 | 2 |
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.