Interview Questions/SQL/User Session Reconstruction from Event Stream

User Session Reconstruction from Event Stream

Preview mode. Log in to edit, run, submit, and save progress.

Medium

Description

You are given a UserEvents table of timestamped events. A new session begins whenever the gap between two consecutive events for the same user exceeds 30 minutes (1800 seconds). The very first event for each user always starts session 1. For each session, compute: user_id, session_num (1-based per user), session_start (earliest event_time), session_end (latest event_time), event_count, and duration_seconds (session_end minus session_start in seconds). Return results ordered by user_id, then session_num. Table: UserEvents

Column NameTypeDescription
event_idINTPrimary key
user_idINTUser identifier
event_timeDATETIMETimestamp of event (ISO format)

Database Schema (Inferred)

UserEvents

Column NameExample Value
event_id1
user_id1
event_time2024-01-01 09:00:00

Example

UserEvents

event_iduser_idevent_time
112024-01-01 09:00:00
212024-01-01 09:10:00
312024-01-01 09:25:00
412024-01-01 10:10:00
512024-01-01 10:20:00
622024-01-01 08:00:00
722024-01-01 08:40:00
822024-01-01 08:50:00

Output

user_idsession_numsession_startsession_endevent_countduration_seconds
112024-01-01 09:00:002024-01-01 09:25:0031500
122024-01-01 10:10:002024-01-01 10:20:002600
212024-01-01 08:00:002024-01-01 08:00:0010
222024-01-01 08:40:002024-01-01 08:50:002600

Explanation:

Use LAG to compare each event to the previous one per user. Mark a new session when the gap > 1800s or there is no previous event. Use SUM(is_new_session) OVER (PARTITION BY user_id ORDER BY event_time) as a session counter. Aggregate per user+session.

Approach hint

Start with a simple approach, explain the trade-off, then move toward a cleaner or more scalable solution.

Common mistake

Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.

SQL Editor
Loading...

UserEvents

event_iduser_idevent_time
112024-01-01 09:00:00
212024-01-01 09:10:00
312024-01-01 09:25:00
412024-01-01 10:10:00
512024-01-01 10:20:00
622024-01-01 08:00:00
722024-01-01 08:40:00
822024-01-01 08:50:00

Output

user_idsession_numsession_startsession_endevent_countduration_seconds
112024-01-01 09:00:002024-01-01 09:25:0031500
122024-01-01 10:10:002024-01-01 10:20:002600
212024-01-01 08:00:002024-01-01 08:00:0010
222024-01-01 08:40:002024-01-01 08:50:002600