Skip to content

Gaps and islands

Find streaks of consecutive days, sessions and missing ranges by subtracting a row number from the value.

Practise: 6 questions

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:

  1. Reduce to one row per user per day. Duplicates break the trick.
  2. Number the rows in time order within each user.
  3. 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.
  4. 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

Variations

In other warehouses

Practise gaps and islands