← All Exercises

Sessionize Page Views with a 30-Minute Timeout

advancedsql~20min

Background

Product analytics needs sessions rather than isolated hits. Sessionization turns an event stream into bounded visits that can be measured for length and engagement.

Problem

Given raw page_views rows, group each user's views into sessions. A new session starts when the gap from the previous view exceeds 30 minutes, and each session reports its start, end, and page count.

Input

A PostgreSQL page_views table with user_id integer NOT NULL, viewed_at timestamptz NOT NULL, and PRIMARY KEY (user_id, viewed_at).

Output

One row per user and session with user_id, session_no starting at 1, session_start, session_end, and page_count, ordered by user and session.

Sample tests

Sample 1

Input: user 1 views at 2026-10-01 09:00, 09:10, 09:50, 10:00 UTC; user 2 views at 09:05 and 09:06 UTC
Expected: 1 | 1 | 09:00 | 09:10 | 2
1 | 2 | 09:50 | 10:00 | 2
2 | 1 | 09:05 | 09:06 | 2

Sample 2

Input: a separate dataset where user 3 has a single view at 2026-10-01 12:00 UTC
Expected: 3 | 1 | 12:00 | 12:00 | 1

Your solution

Learning objective

Build a two-stage window pipeline: detect boundaries with LAG, then number groups with a cumulative SUM.