Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 79/ 160
04. Subqueries & Common Table Expressions (CTEs)

Sessionization Queries (Grouping User Events by Inactivity Timeout)

Group clickstream events into sessions using inactivity thresholds.

AdvancedSession Timeout · Event Streams3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Sessionizing events (PostgreSQL)Query example
1Input dataStart from the source rows or state that the statement sees.
events
3 rows
events sample rows
idcreated_atarchived
12024-11-20false
22024-12-15false
32026-01-05false
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1WITH2  g AS (3    SELECT4      user_id,5      ts,6      CASE7        WHEN LAG(ts) OVER w IS NULL8        OR ts - LAG(ts) OVER w > interval '30 minutes' THEN 19        ELSE 010      END AS new_session11    FROM12      events13    WINDOW14      w AS (15        PARTITION BY16          user_id17        ORDER BY18          ts19      )20  )21SELECT22  user_id,23  ts,24  SUM(new_session) OVER (25    PARTITION BY26      user_id27    ORDER BY28      ts ROWS UNBOUNDED PRECEDING29  ) AS session_no30FROM31  g;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/31
3OutputInspect the representative rows, affected-row count, plan, or command status.
Numbered user sessions4 sample rows
Numbered user sessions
user_idtssession_no
72026-11-21 09:00:001
72026-11-21 09:15:001
72026-11-21 10:00:002
92026-11-21 14:00:001

Note: Uses a 30-minute inactivity threshold; timestamps are illustrative.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Session summaryQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  user_id,3  session_no,4  MIN(ts) AS started,5  MAX(ts) - MIN(ts) AS duration,6  COUNT(*) AS events7FROM8  sessionized9GROUP BY10  user_id,11  session_no;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/11
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative session summary3 sample rows
Representative session summary
user_idsession_nostarteddurationevents
712026-11-21 09:00:0000:15:002
722026-11-21 10:00:0000:00:001
912026-11-21 14:00:0000:12:003

Note: Assumes the sessionized relation contains the shown event groups; interval formatting is PostgreSQL-style and dialect-dependent.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Group by (user, session number) for durations, counts and bounces.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Window

Order events per user

Partition by user and order by timestamp, with an event id as a tiebreaker.

SQL at this step
1PARTITION BY2  user_id3ORDER BY4  ts,5  event_id
What to watch at this step
Per
user
Tip: use ← → to move between steps

When 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

Inactivity timeout (LAG + running SUM)
Best for: Clickstream and app event data

Strengths: Standard, flexible, runs in one pass per window.

Watch out: The timeout is a judgement call.

Fixed calendar buckets (per day)
Best for: Rough daily engagement

Strengths: Very simple.

Watch out: Splits real sessions at midnight and merges separate visits.

Client-generated session ids
Best for: When the app or SDK already sends a session id

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?
Interview tip: Draw four timestamps with one big gap and walk through the gap, flag and running-sum columns. Interviewers follow it instantly, and it shows you understand why the running sum works.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Identifying Gaps and Islands in Sequential Data
Next topic
Structuring Production Analytical SQL Models