In two sentences
An island is a run of consecutive rows (days in a row, clicks close together) and a gap is where the run
breaks. The trick is to give every row in the same run the same group id, and then a plain GROUP BY measures
each run.
See it
One user's login days. Subtract the row number from the date, and every streak lands on the same value:
| login_date | row_number | date − row_number | streak |
|---|---|---|---|
| 03-01 | 1 | 02-28 | A |
| 03-02 | 2 | 02-28 | A |
| 03-03 | 3 | 02-28 | A |
| 03-05 | 4 | 03-01 | B |
| 03-06 | 5 | 03-01 | B |
The date goes up by 1 each day and so does the row number, so their difference stays constant inside a streak and jumps at a gap. Streak A is 3 days, streak B is 2.
In SQL
Streaks (consecutive days):
WITH days AS (
SELECT DISTINCT user_id, CAST(login_ts AS date) AS d -- one row per day first!
FROM logins
),
grouped AS (
SELECT user_id, d,
date_add('day', -row_number() OVER (PARTITION BY user_id ORDER BY d), d) AS grp
FROM days
)
SELECT user_id, min(d) AS streak_start, max(d) AS streak_end, count(*) AS days
FROM grouped
GROUP BY user_id, grp;Sessions (a new session after 30 minutes of silence) use the second shape: flag the starts, then count them.
WITH flagged AS (
SELECT *,
CASE WHEN lag(event_ts) OVER (PARTITION BY user_id ORDER BY event_ts) IS NULL
OR date_diff('minute', lag(event_ts) OVER (PARTITION BY user_id ORDER BY event_ts), event_ts) > 30
THEN 1 ELSE 0 END AS is_start
FROM clicks
)
SELECT *,
sum(is_start) OVER (PARTITION BY user_id ORDER BY event_ts
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS session_number
FROM flagged;The running sum of start flags is the island id. This shape works for any "a new group starts when…" rule.
Common mistakes
- Not deduplicating days first. Two logins on 03-02 give two row numbers for one day and break the arithmetic.
- Using
rankinstead ofrow_number. Ties make the numbers skip, and the groups split. - Boundaries off by one. Is a gap of exactly 30 minutes a new session? Read the rule;
>and>=differ. - Overlapping intervals. Alerts with start and end times overlap, so "the previous row ended" isn't enough. Compare
with the running
max(end)of everything before, not just the previous row.
What an interviewer asks next
- "Longest streak per user?" Wrap the query and take
max(days)per user. - "Sessions across midnight?" The session belongs to the day it started; say so explicitly.
Go further
The Redgate article walks through both gaps and islands with diagrams; the T-SQL translates directly to Trino.
Practise it
Longest Consecutive-Day Streak per User, then Sessionize a Clickstream, then Merge Overlapping Alerts into Outages (hard).