When you need it
"Longest streak of daily activity", "group events into sessions with a 30 minute gap", "periods when an account was continuously active", "which days are missing". Words that signal it: "consecutive", "streak", "in a row", "session", "gap", "continuous", "missing".
An island is a run of consecutive rows. A gap is the hole between two islands. The trick is to give every row in an island the same label so you can group by it.
The shape of the query
with d as (
select distinct user_id, day from activity
),
labelled as (
select user_id, day,
day - (row_number() over (partition by user_id order by day))::int as island
from d
)
select user_id, min(day) as start_day, max(day) as end_day, count(*) as days
from labelled
group by user_id, island;Step by step:
- Reduce to one row per user per day. Duplicates break the trick.
- Number the rows in time order within each user.
- Subtract the row number from the date. In a run of consecutive days both go up by one, so the difference stays constant. When a day is skipped, the difference jumps.
- Group by user and that constant. Each group is one island: take the min, max and count.
with d as (
select distinct listener_id, played_at::date as day
from plays
),
labelled as (
select listener_id, day,
day - (row_number() over (partition by listener_id order by day))::int as island
from d
)
select listener_id,
min(day) as streak_start,
max(day) as streak_end,
count(*) as streak_days
from labelled
group by listener_id, island
having count(*) >= 3
order by streak_days desc, listener_id, streak_start
limit 10;Sessions use a different label: start a new session whenever the gap from the previous row exceeds a limit, then take a running sum of those starts.
with ordered as (
select user_id, occurred_at,
case when occurred_at - lag(occurred_at) over (partition by user_id order by occurred_at)
> interval '30 minutes'
then 1 else 0 end as new_session
from events
), numbered as (
select user_id, occurred_at,
sum(new_session) over (partition by user_id order by occurred_at
rows between unbounded preceding and current row) as session_no
from ordered
)
select user_id, session_no, min(occurred_at) as started, count(*) as events
from numbered
group by user_id, session_no
order by user_id, session_no
limit 10;The first row per user has a NULL lag, the comparison is NULL, and the CASE returns 0, so session 0 starts without a special case.
Traps interviewers look for
- Duplicate days. Two rows on one day make the row number outrun the date and split a streak in two. Use
distinctor group by day first. row_numberversusrank. The trick needs a number that always rises by exactly one.rankrepeats values and breaks it.- Ordering inside the window. Order by the date, and partition by the entity. Missing the partition mixes users.
- Date type.
date - integergives a date in PostgreSQL. With timestamps, cast to date first. - Weeks and months. For consecutive weeks or months, number the periods (truncate first) and subtract in the same unit.
- Off by one in the gap. The gap between island A (ends on the 5th) and island B (starts on the 9th) is the 6th to the 8th, so the gap starts at
end + 1and stops atnext_start - 1. - Deciding what a streak means. Does a day with zero activity break it? Is a 30 minute gap strict (
>) or not (>=)? State it.
Variations
- Longest streak. Aggregate the islands, then take the maximum per user, with ties handled as in the ranking lesson.
- Current streak. Keep the island that ends on the latest date.
- Missing dates. Left join a calendar and keep the NULL side, then label the missing runs the same way.
- Gap list with
LEAD.lead(day) over (...) - day > 1flags where an island ends. - Status periods. Collapse consecutive rows with the same status into one range.
In other warehouses
- Date minus integer. PostgreSQL does it directly. Snowflake, BigQuery, SQL Server and MySQL need
DATEADD(day, -rn, day),DATE_SUB(day, INTERVAL rn DAY)and so on. Group by the resulting date. - Interval comparisons. Write
occurred_at - lag(...) > interval '30 minutes'in PostgreSQL. In Snowflake and SQL Server, compareDATEDIFF(minute, prev, occurred_at) > 30. BigQuery usesTIMESTAMP_DIFF(occurred_at, prev, MINUTE) > 30. DATEDIFF(minute, ...)counts minute boundaries crossed, so 29:59 can read as 30. Use seconds when precision matters.