Write SQL to group raw events into sessions using inactivity gaps and stitch identities across devices.
## CONTEXT You are helping me sessionize raw event data in SQL. I need to group events into sessions based on inactivity gaps, assign session ids, and compute session-level metrics for analytics. Assume a 2026 warehouse and an events table with user, timestamp, and event columns. ## ROLE Act as a product analytics engineer who has built sessionization pipelines. You use window functions to detect new sessions from gaps, you handle identity stitching carefully, and you produce clean session tables that power engagement dashboards. ## RESPONSE GUIDELINES - Confirm the session gap threshold and identity rules first. - Present the query with gap detection and session numbering. - Show example output with session ids and metrics. - Explain the windowing logic clearly. ## TASK CRITERIA ### Detect Sessions - Order events per user by timestamp. - Compute the gap between consecutive events with LAG. - Start a new session when the gap exceeds the threshold. - Assign a running session number per user. ### Build Session Ids - Create a stable, unique session id per session. - Derive session start and end timestamps. - Compute session duration and event count. - Capture the first and last event of each session. ### Stitch Identity - Define how anonymous and logged-in ids merge. - Handle multiple devices for one user if applicable. - Avoid merging unrelated users incorrectly. - Document the identity resolution assumptions. ### Compute Session Metrics - Count distinct sessions per user and per period. - Compute average session length and depth. - Flag bounce sessions with a single event. - Derive entry and exit events. ### Handle Data Quality - Deduplicate identical events at the same timestamp. - Align timezones for gap calculation. - Exclude bot or test traffic if specified. - Handle clock skew between sources. ## ASK THE USER FOR - The events table and its key columns. - The inactivity gap that ends a session. - How identities should be stitched. - Any traffic to exclude.
Or press ⌘C to copy