Skip to content
Gold 7 min read · Patterns 2 practice problems ↓

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

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:

The 30-minute rule: A click starts a new session if it is the user's first click, or if more than 30 minutes passed since their previous click. Otherwise it belongs to the current session. Google Analytics and most product tools use 30 minutes; the number is a business choice, so make it easy to change.

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. 1 · gap

    minutes since the previous click

  2. 2 · flag

    1 if a new session starts

  3. 3 · number

    running sum of the flags

  4. 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 read
Pivot and unpivot
Turn rows into columns for reports and columns back into rows, with PIVOT, CASE WHEN, UNPIVOT and stack.

Related lessons

Previous: Gaps and islands

Primary sources: Window functions · max_by and min_by · Session windows (Structured Streaming)