DataLane

21. Sessionize events (30-minute gap)

hardProNot started~20 minSessionizationWindow functions

Asked in screens shaped like: Netflix, Spotify, Airbnb

Group each customer’s events into sessions that break after 30 minutes of inactivity. This is the three-step gap-and-island pattern: look back, flag a break, then accumulate the flag into an id.

Requirements

  • Columns: customer_id, occurred_at, session_id
  • session_id restarts at 1 for every customer
  • A new session starts on the first event or when the gap from the previous event exceeds 30 minutes
  • Order by customer_id, then occurred_at

Expected output

customer_id, occurred_at, session_id

Row order is graded, so ORDER BY matters here.

SQL editor

Loading SQL engine…

Ctrl/Cmd + Enter submits

Run your query to see the result set.

Pro problem

Hard problems unlock with Pro

Easy pads stay free. Medium and hard SQL and Python problems — editor, tests, hints, and solutions — open after you upgrade to Pro or coaching.

See plansPractice free easy problems
↑↓ navigate openesc close