Sessionization Queries (Grouping User Events by Inactivity Timeout)
Group clickstream events into sessions using inactivity thresholds.
In plain words
If a user does nothing for more than 30 minutes, the next thing they do starts a new visit. Number the visits by counting those restarts.
Think of it like…
Reading a chat history: if someone goes quiet for more than half an hour and then writes again, you treat it as a new conversation rather than part of the old one.
Where you’ve seen it
Pages per session per day for a content site: sessionize page_view events with a 30-minute timeout, then count events per session and average them by day. The same steps give session duration (last event − first event) and bounce rate (sessions with one event).
Words you’ll hear
- Inactivity timeout
- The gap that ends a session, such as 30 minutes.
- New-session flag
- 1 when an event starts a session (first event, or gap > timeout), else 0.
- Running sum
- SUM(flag) OVER (PARTITION BY user ORDER BY ts) numbers the sessions.
- Session id
- A combination like user_id + session number that identifies a session.
Visual diagram
Theory & example queries
The three-step pattern
Step 1: for each event, get the previous event's time for the same user with LAG(ts) OVER (PARTITION BY user_id ORDER BY ts). Step 2: flag a new session when there's no previous event or the gap exceeds the timeout. Step 3: a running sum of the flags per user, SUM(flag) OVER (PARTITION BY user_id ORDER BY ts), gives 1, 1, 1, 2, 2 … which is the session number.
This is the general "islands defined by a rule" technique: any condition that starts a new group (a gap, a change of page category, a new campaign) can become the flag, and the running sum turns flags into group numbers.
| id | created_at | archived |
|---|---|---|
| 1 | 2024-11-20 | false |
| 2 | 2024-12-15 | false |
| 3 | 2026-01-05 | false |
WITH g AS ( SELECT user_id, ts, CASE WHEN LAG(ts) OVER w IS NULL OR ts - LAG(ts) OVER w > interval '30 minutes' THEN 1 ELSE 0 END AS new_session FROM events WINDOW w AS ( PARTITION BY user_id ORDER BY ts ) )SELECT user_id, ts, SUM(new_session) OVER ( PARTITION BY user_id ORDER BY ts ROWS UNBOUNDED PRECEDING ) AS session_noFROM g;PostgreSQL is the lesson baseline unless noted otherwise.
Read this line together with the surrounding statement as part of the same SQL expression.
Numbered user sessions4 sample rows
| user_id | ts | session_no |
|---|---|---|
| 7 | 2026-11-21 09:00:00 | 1 |
| 7 | 2026-11-21 09:15:00 | 1 |
| 7 | 2026-11-21 10:00:00 | 2 |
| 9 | 2026-11-21 14:00:00 | 1 |
Note: Uses a 30-minute inactivity threshold; timestamps are illustrative.
Key takeaway: LAG for gaps, a flag for new sessions, a running SUM for session numbers.
Session metrics and edge cases
Once each event has a session number, GROUP BY user_id, session_no to get each session's start (MIN(ts)), end (MAX(ts)), duration and event count. Note that a single-event session has a duration of 0, and the time spent on the last page is unknown, which every analytics tool has to approximate.
Choose the timeout to suit the product (30 minutes is common for websites; mobile apps often use shorter ones) and keep it consistent. Decide whether sessions should also split at midnight or when the traffic source changes, as some analytics tools do. Events with identical timestamps need a tiebreaker in ORDER BY so the running sum is deterministic.
SELECT user_id, session_no, MIN(ts) AS started, MAX(ts) - MIN(ts) AS duration, COUNT(*) AS eventsFROM sessionizedGROUP BY user_id, session_no;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Representative session summary3 sample rows
| user_id | session_no | started | duration | events |
|---|---|---|---|---|
| 7 | 1 | 2026-11-21 09:00:00 | 00:15:00 | 2 |
| 7 | 2 | 2026-11-21 10:00:00 | 00:00:00 | 1 |
| 9 | 1 | 2026-11-21 14:00:00 | 00:12:00 | 3 |
Note: Assumes the sessionized relation contains the shown event groups; interval formatting is PostgreSQL-style and dialect-dependent.
Key takeaway: Group by (user, session number) for durations, counts and bounces.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Order events per user
Partition by user and order by timestamp, with an event id as a tiebreaker.
PARTITION BY user_idORDER BY ts, event_idWhen to use it & trade-offs
What it is
Sessionization groups each user's events into sessions: a new session starts whenever the gap since that user's previous event is longer than a timeout, commonly 30 minutes. In SQL: compare each event with the previous one using LAG, flag the starts of new sessions, and number the sessions with a running SUM of those flags.
Why it matters: Raw clickstream data has no session id, yet questions like "average session length", "pages per session" and "sessions per user per day" depend on one. It's a classic senior analytics interview problem because it combines LAG, a running sum and careful grouping.
When to reach for it
- Session counts, durations and pages per session
- Bounce rate (sessions with one event)
- Attributing conversions to the session they happened in
When to avoid or be careful
- Sessionizing without PARTITION BY user
- Changing the timeout between reports
- Ordering by timestamp alone when events can share a timestamp
Ways to define sessions
Strengths: Standard, flexible, runs in one pass per window.
Watch out: The timeout is a judgement call.
Strengths: Very simple.
Watch out: Splits real sessions at midnight and merges separate visits.
Strengths: No inference needed.
Watch out: Depends on client logic being consistent across platforms.
Interview signals & numbers to know
When this topic comes up
- “Group events into sessions”
- “Average session length”
- “30 minutes of inactivity”
- Clickstream analysis
- Islands defined by a rule
Benchmarks & rules of thumb
- 30 min
- common web session timeout
- 3
- steps: LAG, flag, running SUM
- 0
- duration of a single-event session
Common mistakes & follow-ups
Common interview mistakes
- Forgetting PARTITION BY user_id, so one user's events continue another user's session.
- Treating the first event as a gap of NULL and never flagging it, so session numbers start at 0.
- Reporting session duration as if it included time on the last page.
Likely interviewer follow-ups
- How would you compute the average number of sessions per user per week?
- How would you also start a new session when the traffic source changes?
- What are the limitations of measuring session duration from events?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Sessionization Queries (Grouping User Events by Inactivity Timeout) with hands-on SQL practice and interview Q&A.