SQL Window Functions: Deduplication, Gaps and Islands, and Sessionization/Flag a new session when the gap is too large
Start a new session after 30 minutes of inactivity.
Section: Gaps and islands
Flag a new session when the gap is too large
sql
sql
WITH flagged AS (
SELECT user_id,
event_time,
CASE
WHEN event_time - LAG(event_time) OVER (
PARTITION BY user_id
ORDER BY event_time
) > INTERVAL '30 minutes'
OR LAG(event_time) OVER (
PARTITION BY user_id
ORDER BY event_time
) IS NULL
THEN 1 ELSE 0
END AS is_new_session
FROM user_events
)
SELECT *
FROM flagged;Explanation
This is the first step in sessionization. Interval syntax may differ by dialect.
Learn the surrounding workflow
Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.
Related commands
Same sheet · prioritizing Gaps and islands
Assign session IDs with a running sum
Convert session boundary flags into stable groups.
Group consecutive dates into streaks
Classic islands pattern using row-number arithmetic.