Mastering Product Analytics with Mixpanel & GA4Lesson 25 of 32
Lesson 25 of 32

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.
Example

Real-World Example: Reading Paragraphs in a Book with Empty Lines

PRACTICAL CONTEXT
  • 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.
Corporate / Tech Term Everyday / Practical Metaphor Operational Meaning
Raw Clickstream Event A single word on a book page One atomic user interaction with a timestamp.
30-Minute Inactivity Window The empty blank line between paragraphs If time gap > 30 mins, mark it as the start of a new session.
`LAG()` Window Function Looking back at the previous word with your finger SQL function that peeks at the timestamp of the row directly above.
Cumulative Sum Session ID Numbering the paragraphs: #1, #2, #3 Assigning a clean incrementing number to each visit.
Core Principle: A session is not a database object—it is a time-bound mathematical construct! The industry standard inactivity window is 30 minutes.

Visual Infographic: The 3-Step SQL Sessionization Pipeline

SQL PIPELINE INFOGRAPHIC
Stage 1
1. Calculate Time Difference

Use `LAG(timestamp)` to find seconds elapsed since previous click.

Stage 2
2. Flag New Sessions

`CASE WHEN diff_minutes > 30 THEN 1 ELSE 0 END AS is_new_session`.

Stage 3
3. Cumulative Sum

`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 IDEvent TimestampEvent NameMinutes Since Prev ClickSession 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 PHASES
1 Product Analyst
Query Raw Event Stream

Pull `user_id`, `event_name`, and `event_timestamp` ordered by user and time.

2 Product Analyst
Calculate Inactivity Gaps

Apply `LAG(event_timestamp) OVER (PARTITION BY user_id ORDER BY event_timestamp)` to find preceding timestamp.

3 Product Analyst
Set 30-Minute Boundary Flag

Create binary flag: If `TIMESTAMP_DIFF(current, previous, MINUTE) >= 30`, flag as 1, else 0.

4 Product Analyst
Generate Incremental Session ID

Wrap in `SUM(is_new_session) OVER (PARTITION BY user_id ORDER BY event_timestamp)`.

5 Product Analyst
Aggregate Session Metrics

Group by `session_id` to compute Total Duration, Pages Viewed per Session, and Bounces.

BigQuery / Snowflake SQL Workspace

Step-by-Step UI Tutorial: Executing Sessionization Query in BigQuery

Step 1
Step 1: Open SQL Workspace

Open Google Cloud BigQuery Console -> Create new SQL tab.

Step 2
Step 2: Paste Common Table Expression (CTE)

Write CTE with `LAG()` to calculate `prev_timestamp` across user event partitions.

Step 3
Step 3: Add Windowed Sum

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`.

Step 4
Step 4: Run & Materialize View

Click "Run" -> Save results as a materialized BigQuery View `prod_user_sessions`.

Production SQL Sessionization Template (BigQuery Syntax)

SQL BLUEPRINT
step Namesql 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

  1. Write the SQL expression using `LAG()` to find the seconds elapsed between a user adding an item to cart and clicking checkout.
  2. 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.