← All SQL interview questions

Sessionise a clickstream with a 30-minute rule

HardCTEsAmazonZoomInfo

Product analytics defines a session as a run of a user's events where no two consecutive events are more than 30 minutes apart. A gap of exactly 30 minutes keeps the session going; a gap of more than 30 minutes starts a new one.

From click_events, return user_id, session_no (1, 2, 3... per user), session_start, session_end, events (number of events) and duration_minutes (end minus start, in minutes, 1 decimal). Order by user_id, then session_no.

Sample data

Table: click_events

17 row(s) · showing first 8

event_idINTuser_idINTevent_timeTIMESTAMPpageTEXT
112026-10-20home
212026-10-20search
312026-10-20product
412026-10-20home
512026-10-20product
612026-10-20cart
722026-10-20home
822026-10-20search