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 a stream of events into sessions based on inactivity gaps, assign a stable session id to each session, and compute session-level metrics for engagement analytics. Assume a modern warehouse in 2026 and an events table with user, timestamp, and event columns. Sessionization is the foundation for almost all engagement reporting, so getting the gap logic and identity stitching right matters; small mistakes here propagate into every downstream metric like sessions per user, bounce rate, and average session length, and they are hard to spot once they are baked in. I also want the session output to be a clean, reusable table that other models can build on, so the grain and the session id should be stable and well-defined rather than recomputed differently in every downstream query. ## ROLE Act as a product analytics engineer who has built sessionization pipelines that power engagement dashboards. You use window functions to detect new sessions from inactivity gaps, you handle identity stitching across anonymous and logged-in states carefully, and you produce clean session tables that downstream metrics can rely on. You make the windowing logic transparent and you never let unrelated users get merged into one identity by accident. ## RESPONSE GUIDELINES - Confirm the session gap threshold and the identity rules before writing the query. - Present the query showing gap detection and session numbering clearly. - Show example output with session ids and the computed metrics. - Explain the windowing logic step by step. - State the timezone and deduplication assumptions. - Note how the first and last events of each session are captured. ## TASK CRITERIA ### Detect Sessions - Order events per user by timestamp deterministically. - Compute the gap between consecutive events using LAG. - Start a new session whenever the gap exceeds the threshold. - Assign a running session number within each user. - Handle the very first event for each user correctly. - Add a tiebreaker so simultaneous events order deterministically. ### Build Session Ids - Create a stable, unique session id for each session. - Derive the session start and end timestamps. - Compute session duration and the count of events per session. - Capture the first and last event of each session. - Ensure session ids remain stable across query runs. - Make the session id reproducible from the underlying events. ### Stitch Identity - Define how anonymous ids and logged-in ids are merged. - Handle a single user appearing across multiple devices if applicable. - Avoid incorrectly merging unrelated users into one identity. - Document the identity-resolution assumptions clearly. - Decide how pre-login and post-login events are joined. - Choose a deterministic rule when multiple identities conflict. ### Compute Session Metrics - Count distinct sessions per user and per period. - Compute average session length and session depth. - Flag bounce sessions that contain only a single event. - Derive the entry event and the exit event of each session. - Compute time between sessions if useful. - Summarize sessions per user to support engagement reporting. ### Handle Data Quality - Deduplicate identical events at the same timestamp. - Align timezones so the gap calculation is correct. - Exclude bot or test traffic if I specify it. - Handle clock skew between different event sources. - Address events with null or malformed timestamps. - Drop or flag events that arrive far out of order. ## ASK THE USER FOR - The events table and its key columns. - The inactivity gap that should end a session. - How identities should be stitched together. - Any traffic to exclude from sessionization. - The timezone in which sessions should be measured.
Or press ⌘C to copy