download

How do you split user events into sessions using LAG()?

SQL~10 minReviewed 3 Dec 2026Free · No sign-in

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_idev_min
110
125
155
186
1100
25
240
270
2120
Show hints (3)
  1. "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.

  2. "FLAG SESSION STARTS"

    Mark a row 1 when prev_min IS NULL or ev_min - prev_min > 30, and 0 otherwise. Keep an exact 30-minute gap in the current session.

  3. "SUM THE FLAGS"

    Take a running SUM() of that 0/1 flag partitioned by user_id and ordered by ev_min. Each 1 increments the user's session_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.

"SOLUTION · SQL"
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;
"OUTPUT"
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_minprev_mingapnew_sessionsession_id
10NULLNULL11
25101501
55253001
86553112
100861402

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 NULL in the CASE expression. Because ev_min - NULL is NULL, the first event gets 0 instead of 1, shifting every session ID down by one.
  • Using >= 30 instead of > 30. That falsely splits user 1 at minute 55 and user 2 at minute 70, even though both gaps equal 30.
  • Omitting PARTITION BY user_id in either LAG() or SUM(). User 2's first event compares against user 1's last event and inherits user 1's session count.
  • Nesting LAG() inside SUM() OVER (...) in one query level. SQL rejects nested window functions; compute LAG() 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. User 1 yields (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_id to both ORDER BY clauses (ORDER BY ev_min, event_id). The second tied row gets gap 0 and 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 checking prev_min IS NULL is 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 →

Original OfferVibe question. SQLite Window Functions · PostgreSQL Window Functions.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.