How do you split user events into sessions using LAG()?
Question
Each row in events records a user and an event time in minutes (ev_min, unique per user). Start a new session when a user has no previous event or the gap from their previous event is greater than 30 minutes (gap > 30). Return user_id, ev_min, and session_id (starting at 1 per user), ordered by user_id, ev_min.
events
| user_id | ev_min |
|---|---|
| 1 | 10 |
| 1 | 25 |
| 1 | 55 |
| 1 | 86 |
| 1 | 100 |
| 2 | 5 |
| 2 | 40 |
| 2 | 70 |
| 2 | 120 |
Show hints (3)
- "READ PREVIOUS TIMESTAMP"
Use
LAG(ev_min) OVER (PARTITION BY user_id ORDER BY ev_min)in a CTE to attach each row's previous event time. - "FLAG SESSION STARTS"
Mark a row
1whenprev_min IS NULLorev_min - prev_min > 30, and0otherwise. Keep an exact30-minute gap in the current session. - "SUM THE FLAGS"
Take a running
SUM()of that0/1flag partitioned byuser_idand ordered byev_min. Each1increments the user'ssession_id.
Show checked explanation
Compute each user's previous timestamp with LAG(ev_min) inside a CTE. Then run a conditional running SUM() that adds 1 when prev_min IS NULL or ev_min - prev_min > 30, and 0 otherwise. That labels every event with a per-user session_id starting at 1.
WITH stepped AS ( SELECT user_id, ev_min, LAG(ev_min) OVER ( PARTITION BY user_id ORDER BY ev_min ) AS prev_min FROM events ) SELECT user_id, ev_min, SUM( CASE WHEN prev_min IS NULL OR ev_min - prev_min > 30 THEN 1 ELSE 0 END ) OVER ( PARTITION BY user_id ORDER BY ev_min ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) AS session_id FROM stepped ORDER BY user_id, ev_min;
user_id | ev_min | session_id 1 | 10 | 1 1 | 25 | 1 1 | 55 | 1 1 | 86 | 2 1 | 100 | 2 2 | 5 | 1 2 | 40 | 2 2 | 70 | 2 2 | 120 | 3
Author-checked on SQLite 3.49.1: ran the published query against the sample table, checked the exact 30-minute vs 31-minute boundary, tested NULL first-event handling, verified per-session summary aggregation, and compared against an iterative Python sessionizer. Checked by an editor other than the author.
Walkthrough
SQL forbids nesting one window function inside another (SUM(LAG(...))), so sessionization uses two passes:
Pass 1 (stepped CTE). LAG(ev_min) reads the preceding row inside each user's timeline. Every user's first event has no predecessor, so prev_min is NULL.
Pass 2 (running SUM). Convert each row into 1 (starts a new session) or 0 (continues the current session), then accumulate per user. Treating prev_min IS NULL as 1 guarantees every user starts at session_id = 1. Here is user 1 step by step:
| ev_min | prev_min | gap | new_session | session_id |
|---|---|---|---|---|
| 10 | NULL | NULL | 1 | 1 |
| 25 | 10 | 15 | 0 | 1 |
| 55 | 25 | 30 | 0 | 1 |
| 86 | 55 | 31 | 1 | 2 |
| 100 | 86 | 14 | 0 | 2 |
Look at the boundary at minute 55. The gap is 55 - 25 = 30, which is not strictly greater than 30, so it stays in session 1. At minute 86, the gap is 31 > 30, so the flag becomes 1 and increments session_id to 2.
User 2 starts fresh at session_id = 1 (ev_min = 5) and opens session 2 after a 35-minute gap (40). Minute 70 stays in session 2 because its gap equals 30, and minute 120 opens session 3 (50-minute gap).
Common mistakes
- Forgetting
prev_min IS NULLin theCASEexpression. Becauseev_min - NULLisNULL, the first event gets0instead of1, shifting every session ID down by one. - Using
>= 30instead of> 30. That falsely splits user1at minute55and user2at minute70, even though both gaps equal30. - Omitting
PARTITION BY user_idin eitherLAG()orSUM(). User2's first event compares against user1's last event and inherits user1's session count. - Nesting
LAG()insideSUM() OVER (...)in one query level. SQL rejects nested window functions; computeLAG()in a CTE first.
Follow-up questions
- "How would you summarize each session into one row with start time, end time, and event count?" Wrap the labeled query in a second CTE and run
SELECT user_id, session_id, MIN(ev_min), MAX(ev_min), COUNT(*) FROM sessions GROUP BY user_id, session_id. User1yields(1, 1, 10, 55, 3)and(1, 2, 86, 100, 2). - "What if two events for the same user share the exact same timestamp?" Add a unique tiebreaker column such as
event_idto bothORDER BYclauses (ORDER BY ev_min, event_id). The second tied row gets gap0and stays in the same session with deterministic ordering. - "Could you avoid checking prev_min IS NULL by passing a default value to LAG()?" Yes,
LAG(ev_min, 1, -31)works for non-negative minute integers, though checkingprev_min IS NULLis safer because it works on any timestamp type without magic sentinel numbers.
What a strong answer covers
Separates LAG() and the running SUM() into two query levels, handles prev_min IS NULL so session 1 starts at 1, enforces > 30 versus == 30, and partitions both windows by user_id.
Open in interactive practice deck →