AlgoMaster Logo

Exercise: Sessionization and Time-Based Grouping

Last Updated: May 12, 2026

1 min read

For this exercise, we will work with below data:

SQL

Exercise 1

Medium

Write a query that returns each stream event with the gap (in minutes) since the previous stream by the same user. Use LAG over started_at partitioned by user_id. Show user_idstream_idstarted_at, and gap_minutes (NULL for each user's first event). Limit to user 1 only. Order by started_at.

SQL

Expected Query

Expected Output