Sessionization Queries: Window Functions to Group Raw Clickstream Events
Overview & Learning Objectives
In raw analytics databases (like Google BigQuery or Snowflake), there is no pre-built column that says "Session #1" or "Session #2". Instead, you just have a giant table with millions of timestamps of button clicks. How do you group those individual clicks into cohesive user browsing sessions? The answer is Sessionization using SQL Window Functions! In this lesson, you will master `LAG()`, calculating inactivity gaps (> 30 minutes), and using cumulative sums to generate unique Session IDs.
- Understand the industry standard 30-minute inactivity session threshold.
- Use `LAG() OVER (PARTITION BY user_id ORDER BY event_timestamp)` to calculate the time gap between consecutive clicks.
- Assign unique Session IDs using a cumulative sum `SUM(is_new_session) OVER (...)` in SQL.
Real-World Example: Reading Paragraphs in a Book with Empty Lines
- Scenario: Grouping sentences in a book into paragraphs separated by blank lines.
- 30-Minute Inactivity Rule: User clickstreams are divided into discrete sessions whenever timestamp gaps exceed 30 minutes.
- SQL Engine: Uses `LAG(event_timestamp)` and cumulative window sums to assign unique session identifiers.
Visual Infographic: The 3-Step SQL Sessionization Pipeline
SQL PIPELINE INFOGRAPHICUse `LAG(timestamp)` to find seconds elapsed since previous click.
`CASE WHEN diff_minutes > 30 THEN 1 ELSE 0 END AS is_new_session`.
`SUM(is_new_session) OVER (PARTITION BY user_id ORDER BY timestamp) AS session_id`.
Industry Standard & Framework
Standard: Google Analytics & BigQuery Clickstream Sessionization Standards.
Real-World Business Application: Hotstar Video Streaming Sessionization Query Audit
Hotstar data engineers reconstruct user watching sessions from raw client-side ping logs to calculate average daily session lengths.
| User ID | Event Timestamp | Event Name | Minutes Since Prev Click | Session ID |
|---|---|---|---|---|
| `usr_101` | 10:00 AM | `app_opened` | NULL (First Event) | `usr_101_sess_1` |
| `usr_101` | 10:05 AM | `cricket_match_clicked` | 5 mins (< 30m) | `usr_101_sess_1` |
| `usr_101` | 10:45 AM | `video_paused` | 40 mins (> 30m BREAK!) | `usr_101_sess_2` |
| `usr_101` | 10:48 AM | `video_resumed` | 3 mins (< 30m) | `usr_101_sess_2` |
Step-by-Step UI Tutorial & Visual Workflow Guide
Below is the practical, non-technical walkthrough showing how Product Analysts design, review, and execute this capability inside real-world tools like Mixpanel, Google Analytics 4, BigQuery, and Google Tag Manager.
Step-by-Step Execution Workflow
EXECUTION PHASESPull `user_id`, `event_name`, and `event_timestamp` ordered by user and time.
Apply `LAG(event_timestamp) OVER (PARTITION BY user_id ORDER BY event_timestamp)` to find preceding timestamp.
Create binary flag: If `TIMESTAMP_DIFF(current, previous, MINUTE) >= 30`, flag as 1, else 0.
Wrap in `SUM(is_new_session) OVER (PARTITION BY user_id ORDER BY event_timestamp)`.
Group by `session_id` to compute Total Duration, Pages Viewed per Session, and Bounces.
Step-by-Step UI Tutorial: Executing Sessionization Query in BigQuery
Open Google Cloud BigQuery Console -> Create new SQL tab.
Write CTE with `LAG()` to calculate `prev_timestamp` across user event partitions.
In outer query, write `SUM(CASE WHEN prev_timestamp IS NULL OR diff_mins >= 30 THEN 1 ELSE 0 END) OVER (PARTITION BY user_id ORDER BY event_timestamp) AS session_id`.
Click "Run" -> Save results as a materialized BigQuery View `prod_user_sessions`.
Production SQL Sessionization Template (BigQuery Syntax)
SQL BLUEPRINT| step Name | sql Snippet |
|---|---|
| Step 1: Lag Calculation | `TIMESTAMP_DIFF(event_timestamp, LAG(event_timestamp) OVER (PARTITION BY user_id ORDER BY event_timestamp), MINUTE) AS inactivity_mins` |
| Step 2: Boundary Marker | `CASE WHEN inactivity_mins IS NULL OR inactivity_mins >= 30 THEN 1 ELSE 0 END AS is_new_session` |
| Step 3: Unique Session ID | `CONCAT(user_id, "_", CAST(SUM(is_new_session) OVER (PARTITION BY user_id ORDER BY event_timestamp) AS STRING)) AS session_id` |
Implementation Guidelines for Product Analysts
- Always partition by `user_id` so timestamps from different users never mix together during window calculations.
- Be mindful of midnight date rollovers: Google Analytics historically reset sessions at midnight, but modern product analytics uses pure 30-minute inactivity.
- Filter out automated background app pings before running sessionization to avoid artificially keeping sessions alive forever.
Practical Hands-On Exercises
- Write the SQL expression using `LAG()` to find the seconds elapsed between a user adding an item to cart and clicking checkout.
- Explain why a 30-minute inactivity rule might create 2 separate sessions if a user watches a 45-minute continuous video without touching the screen.