Interview Questions/SQL/Identify User Sessions from Page View Events

Identify User Sessions from Page View Events

Preview mode. Log in to edit, run, submit, and save progress.

Medium

Description

You are given a PageViews table. A new session begins when the gap between two consecutive page views for the same user exceeds 30 minutes (1800 seconds). Write a SQL query to identify all sessions per user. For each session return: user_id, a sequential session_id (starting at 1 per user), the session_start timestamp, the session_end timestamp, and the page_views count. Return the result ordered by user_id, then session_id. Table: PageViews

Column NameTypeDescription
idINTPrimary key
user_idINTID of the user
viewed_atDATETIMETimestamp of the page view

Database Schema (Inferred)

PageViews

Column NameExample Value
id1
user_id1
viewed_at2023-01-01 10:00:00

Example

PageViews

iduser_idviewed_at
112023-01-01 10:00:00
212023-01-01 10:10:00
312023-01-01 10:25:00
412023-01-01 11:10:00
512023-01-01 11:20:00
622023-01-01 09:00:00
722023-01-01 09:35:00

Output

user_idsession_idsession_startsession_endpage_views
112023-01-01 10:00:002023-01-01 10:25:003
122023-01-01 11:10:002023-01-01 11:20:002
212023-01-01 09:00:002023-01-01 09:00:001
222023-01-01 09:35:002023-01-01 09:35:001

Explanation:

User 1: gap between 10:25 and 11:10 is 45 min > 30 min → new session. User 2: gap between 09:00 and 09:35 is 35 min > 30 min → new session.

Approach hint

Start with a simple approach, explain the trade-off, then move toward a cleaner or more scalable solution.

Common mistake

Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.

SQL Editor
Loading...

PageViews

iduser_idviewed_at
112023-01-01 10:00:00
212023-01-01 10:10:00
312023-01-01 10:25:00
412023-01-01 11:10:00
512023-01-01 11:20:00
622023-01-01 09:00:00
722023-01-01 09:35:00

Output

user_idsession_idsession_startsession_endpage_views
112023-01-01 10:00:002023-01-01 10:25:003
122023-01-01 11:10:002023-01-01 11:20:002
212023-01-01 09:00:002023-01-01 09:00:001
222023-01-01 09:35:002023-01-01 09:35:001