SQL Dojo
Pattern

Sessionization: cut events into sessions

Cut a stream of events into sessions: a new session starts after 30 minutes of silence, found with LAG and numbered with a running SUM.

You need it when a log has events but no session id, and the question is per visit: sessions per user, their length, the first page of each.

WITH flagged 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 0 ELSE 1 END AS new_session
  FROM events
)
SELECT user_id, occurred_at,
       SUM(new_session) OVER (PARTITION BY user_id ORDER BY occurred_at) AS session_no
FROM flagged;

Each event looks back at the user's previous one: a gap of more than 30 minutes, or no previous event, opens a session and is worth 1. The running total of those 1s is the session number; then GROUP BY user_id, session_no.

The trap. Writing the test the other way round, > INTERVAL '30 minutes' THEN 1 ELSE 0. For each user's first event LAG is NULL, the comparison is not true, and the event falls into ELSE 0: the first session is numbered 0, and the count of sessions is one short per user. Test the case that continues a session, so that NULL lands in ELSE 1.

On your warehouse. Postgres and DuckDB subtract timestamps as above. Elsewhere, compute prev_at with LAG first: Snowflake writes DATEDIFF(second, prev_at, occurred_at) <= 1800, BigQuery TIMESTAMP_DIFF(occurred_at, prev_at, SECOND) <= 1800, Databricks timestampdiff(SECOND, prev_at, occurred_at) <= 1800.

WITH events(user_id, occurred_at) AS (VALUES
  (1, TIMESTAMP '2026-06-01 09:00:00'),
  (1, TIMESTAMP '2026-06-01 09:12:00'),
  (1, TIMESTAMP '2026-06-01 09:40:00'),
  (1, TIMESTAMP '2026-06-01 11:05:00'),
  (1, TIMESTAMP '2026-06-01 11:20:00'),
  (2, TIMESTAMP '2026-06-01 10:00:00'),
  (2, TIMESTAMP '2026-06-01 10:45:00')),
flagged 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 0 ELSE 1 END AS new_session
  FROM events
)
SELECT user_id, occurred_at, new_session,
       SUM(new_session) OVER (PARTITION BY user_id ORDER BY occurred_at) AS session_no
FROM flagged
ORDER BY user_id, occurred_at;
user_idoccurred_atnew_sessionsession_no
12026-06-01 09:00:0011
12026-06-01 09:12:0001
12026-06-01 09:40:0001
12026-06-01 11:05:0012
12026-06-01 11:20:0002
22026-06-01 10:00:0011
22026-06-01 10:45:0012
Try it in Randori