AlgoMaster Logo

Exercise: LAG, LEAD, and Row Comparison

Last Updated: May 12, 2026

1 min read

For this exercise, we will work with below data:

SQL

Exercise 1

Easy

Write a query that uses LAG() over streams ordered by started_at ascending to return the previous stream's started_at alongside each row. Return stream_idstarted_at, and prev_started_at. Order by started_at.

SQL

Expected Query

Expected Output

Exercise 2

Easy

Write a query that uses LEAD() over streams ordered by started_at ascending to return the next stream's started_at alongside each row. Return stream_idstarted_at, and next_started_at. Order by started_at. Limit to the first 5 rows of output.

SQL

Expected Query

Expected Output

Exercise 3

Medium

Write a query that uses LAG(started_at) partitioned by user_id to compute the gap in days between each of alice_m's (user_id = 1) consecutive streams. Return stream_idstarted_at, and days_gap (integer day component of the interval). Order by started_at.

SQL

Expected Query

Expected Output