SQL for analysis · senior
Sessionisation from a click stream
A session is a group of events with no gap longer than a timeout between them. Use LAG to find the gaps, a running SUM of new-session flags to number sessions, then aggregate per session.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- LAG(event_time) OVER (PARTITION BY user_id ORDER BY event_time) gives the previous click of the same user.
- A new-session flag is 1 when there is no previous click or the gap is more than the timeout (30 minutes is a convention, and the default in Google Analytics).
- Session number is a running SUM(flag) OVER (PARTITION BY user_id ORDER BY event_time). The session id is the user id plus that number.
- Per session: MIN and MAX time and the count of clicks. Length is max minus min.
- A session with one click has length 0. These pull the average down, so show the median too.
- Give a session that crosses midnight to the day it started, in IST, and say so.
- Choose the timeout from the data. A histogram of gaps between clicks often shows a dip.
- For hourly runs, reprocess a few hours of overlap, because a session still open at the last run may continue.
The red pen
Common traps: mistake → fix
Mistake: Group by user and hour is a session
Fix: a session can cross the hour, and an hour can hold many sessions.
Mistake: LAG without PARTITION BY user_id is fine
Fix: the gap would be measured from another user's click.
Mistake: 30 minutes is a rule of nature
Fix: it is a convention; check the data.
Easy to hard
Questions interviewers ask, easy to hard
- How would you define a session in SQL?
- Why do you need two window functions to number sessions?
- How do single-click sessions affect the average session length?
- How do you handle a session that crosses midnight?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.