Quick revision
The short answer
Use LAG(viewed_at) per user to get the previous view, flag a row as a new session when there is no previous view or the gap is more than 30 minutes, and turn those flags into session numbers with a running SUM over the same window. Grouping by user and session number with MIN, MAX and COUNT gives each session's start, end and number of views.
What to remember
In this answer, we flagged the start of each session by comparing every view with the previous one through LAG, numbered sessions with a running SUM of those flags, and grouped by user and session number to get start, end and view count. We added an index on (user_id, viewed_at) for speed and saw how to run the job hourly by reopening sessions that may continue across the batch boundary.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Use LAG(viewed_at) per user to get the previous view, flag a row as a new session when there is no previous view or the gap is more than 30 minutes, and turn those flags into session numbers with a running SUM over the same window. Grouping by user and session number with MIN, MAX and COUNT gives each session's start, end and number of views.
Why this question is asked
Sessionization is the bread and butter of product analytics: time on site, pages per session, funnel conversion and bot detection all start with it. It is also a perfect interview problem, because it combines the two most useful window function ideas, looking at the previous row and keeping a running total, into a pattern that applies to many other problems. In this answer, we will recap the session rule, compute the gap to the previous view, flag session starts, number the sessions with a running sum, aggregate them, and then talk about performance and running the job incrementally.
1A Quick Recap of the Session Rule
A session is a burst of activity by one user. The rule in the question is the most common one: a view belongs to the current session if it happens at most 30 minutes after the user's previous view, and a gap of more than 30 minutes starts a new session. So sessions are decided per user, in time order, by looking at one neighbour at a time.
That is exactly what LAG is for. LAG(viewed_at) OVER (PARTITION BY user_id ORDER BY viewed_at) returns the previous view time of the same user, or NULL for the user's very first view.
2Flagging Where Sessions Start
We compute a flag that is 1 when a row starts a new session and 0 otherwise. Let us use a small example: user 1 views pages at 09:00, 09:10, 09:55 and 10:05.
The named WINDOW clause saves us from repeating the same partition and order three times. Subtracting two timestamptz values gives an interval, which we can compare directly with INTERVAL '30 minutes'. Notice the boundary: a gap of exactly 30 minutes is not greater than 30 minutes, so it stays in the session. That is a detail worth stating out loud, because product teams often have an opinion about it.
3Numbering Sessions With a Running Sum
The flags mark where sessions begin. If we add them up from the user's first view to the current row, every row gets the number of sessions started so far, which is its session number.
- Order each user's views by timePARTITION BY user_id ORDER BY viewed_at
- Get the previous view
LAG(viewed_at) - Gap missing or over 30 minutes?Yesflag 1, a new session startsNoflag 0, same session
- Running SUM of flagsgives session_no
- GROUP BY user_id, session_noMIN, MAX, COUNT
5 steps in order. Play them, or step through them one at a time.
The reason we write ROWS UNBOUNDED PRECEDING is that the default frame with ORDER BY is RANGE, which treats rows with the same timestamp as peers and adds their flags together. It does not change the result here, because a duplicate timestamp always has a flag of 0, but stating ROWS makes the running total row by row and is explicit about what we mean. We cannot nest LAG inside SUM in one SELECT, which is why the flags live in their own CTE.
4Making It Fast on Large Tables
Every step needs the rows of one user in time order. An index on (user_id, viewed_at) lets PostgreSQL read them in that order instead of sorting the whole table, and it also serves the filter when we restrict the query to a time range. On a table with billions of views, recalculating every session on every report is wasteful, so most teams run sessionization as a batch job that writes a sessions table, and reports read that table.
But there is a catch when we process data in batches: a session can cross the batch boundary. If the 10:00 batch ends with a view at 09:58 and the next batch starts with a view at 10:05, those belong to the same session, and a job that only looks at its own hour would split it in two.
5Running It Incrementally Every Hour
The usual fix is overlap. For each run, we find the sessions that might still be open, meaning their last view is less than 30 minutes before the previous watermark, and we reprocess from the start of the earliest such session instead of from the watermark itself. We then replace those sessions and insert the new ones in one transaction.
Late-arriving events make this harder, because a view stamped 09:40 might arrive at 11:00. We either reprocess a longer window, such as the last few hours, or keep a small allowed lateness and accept rare splits. Streaming engines such as Flink and Kafka Streams offer session windows with a gap and an allowed lateness, which implement the same logic continuously.
6Follow-up questions
How would you run this incrementally every hour?
Keep a watermark of the last processed time and a sessions table. On each run, reopen the sessions whose last view is within 30 minutes of the watermark, delete them, sessionize the raw views from the earliest reopened start onward, and insert the results in one transaction before advancing the watermark. Add a lookback for late events, and make the job idempotent so a rerun of the same hour gives the same sessions.
Why not use date_trunc to bucket views into 30 minute slots?
Fixed buckets cut sessions at clock boundaries. Two views at 09:29 and 09:31 are two minutes apart but would land in different buckets. The rule is about the gap between neighbouring views, which only LAG captures.
How would this look in MySQL 8?
Almost the same. MySQL 8 has LAG, SUM as a window function and named windows. The gap test becomes viewed_at > prev_at + INTERVAL 30 MINUTE or TIMESTAMPDIFF(MINUTE, prev_at, viewed_at) > 30.
7Conclusion
In this answer, we flagged the start of each session by comparing every view with the previous one through LAG, numbered sessions with a running SUM of those flags, and grouped by user and session number to get start, end and view count. We added an index on (user_id, viewed_at) for speed and saw how to run the job hourly by reopening sessions that may continue across the batch boundary.
Open with
I would solve it in three steps with window functions. First, for every view I take the previous view time of the same user with LAG over PARTITION BY user_id ORDER BY viewed_at.
Then, if they want more
I set a flag to one when there is no previous view or when the difference is greater than interval 30 minutes, which means a new session starts, and zero otherwise; I would confirm whether exactly 30 minutes counts as the same session.
Second, I turn the flags into session numbers with a running SUM of the flag over the same partition and order, with ROWS UNBOUNDED PRECEDING so it is a strict row-by-row running total. Each row then carries its user's session number.
Third, I group by user_id and session number and take MIN of viewed_at as the start, MAX as the end and COUNT as the number of views.
For performance, I would have an index on user_id and viewed_at so the rows come out pre-sorted, and on a big table I would write the results into a sessions table from a batch job instead of computing them on every report.
The tricky part of batching is that sessions cross the batch boundary, so each hourly run reopens sessions whose last view is within 30 minutes of the watermark, reprocesses from their start, and replaces them in one transaction, with some lookback for late events.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- MySQL 8
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- PostgreSQL documentation, The SQL Language
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Table page_view(user_id int, viewed_at timestamptz). Split each user's views into...": https://scrivio-interview-library.netlify.app/databases/sql-coding-problems/f6e498eb3c/