Gap And Islands Consecutive Sessions

Identify consecutive session groups using the gap and islands technique with row number difference for grouping.

SqlData Integrity

Code

sqlsnippet
22 lines
WITH numbered AS (
  SELECT
    user_id,
    session_date,
    ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY session_date) AS rn
  FROM user_sessions
),
grouped AS (
  SELECT
    user_id,
    session_date,
    session_date - rn AS grp
  FROM numbered
)
SELECT
  user_id,
  MIN(session_date) AS start_date,
  MAX(session_date) AS end_date,
  COUNT(*) AS consecutive_days
FROM grouped
GROUP BY user_id, grp
ORDER BY user_id, start_date;

How it works

What runs is SELECT, with user_sessions, numbered and grouped as the object involved.

Mechanically, the statements are built from: a CTE (WITH … AS) that names an intermediate result before the main query; COUNT, MIN, MAX aggregation; a GROUP BY that collapses matching rows into one output row per group; a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order.

What to watch for

  • Window functions evaluate after WHERE/GROUP BY, so filtering on their output in the same-level WHERE will not work — use an outer query or a CTE.

Using it

The user_sessions table is the working surface here.

Interactive Tools for This Topic

FAQ

Which tables appear in this script?
`user_sessions`, `numbered`, `grouped`.