Sessionization
Split a clickstream into sessions with an inactivity timeout, then measure each session.
Foundations · SQL for data engineers · Gold · Interview patterns, lesson 2 of 3
On this page
Read first: Gaps and islands (skip if you know it)
In plain words first
Asha opens the app at 10:00, browses until 10:20, leaves, and comes back at 11:30. That is two visits, but the click log is just one list of timestamps. A session is one visit, and the usual rule is:
In SQL this is three small steps, each one a CTECTE: A common table expression: a named step of a query, written WITH name AS (...), that later steps use like a table. Learn more →:
-
1 · gap
minutes since the previous click
-
2 · flag
1 if a new session starts
-
3 · number
running sum of the flags
-
4 · summarise
one row per session
Unlock the full lesson
You have read the free part. The rest of this advanced lesson:
- Step 1: minutes since the previous click
- Steps 2 and 3: flag and number the sessions
- Step 4: one row per session
- Sessions in production
- Common mistakes
- Key takeaways
- Interview prep with 3 follow-up questions
- Check yourself: 4 questions
Unlock it with the Complete pass (every advanced problem and lesson) or on its own.
Practise this
Problems that use this, graded on hidden tests
Keep going
Up next · Interview patterns · lesson 3 of 3 · 6 min readPivot and unpivot
Turn rows into columns for reports and columns back into rows, with PIVOT, CASE WHEN, UNPIVOT and stack.
Related lessons
Gaps and islandsSQL for data engineers · 6 min read
LAG and LEADSQL for data engineers · 7 min read
Running totals and window frames
Previous: Gaps and islands
Primary sources: Window functions · max_by and min_by · Session windows (Structured Streaming)