AlgoMaster Logo

Exercise: FIRST_VALUE, LAST_VALUE, NTH_VALUE

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 FIRST_VALUE(t.title) partitioned by s.user_id ordered by s.started_at to return each stream alongside the first track that user ever played. Return stream_idusernamecurrent_track, and first_track. Order by username, then started_at.

SQL

Expected Query

Expected Output

Exercise 2

Medium

Write a query that uses NTH_VALUE(t.title, 2) with ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING partitioned by s.user_id to return each user's second-ever track. Return stream_idusernamecurrent_track, and second_track. Order by username, then started_at.

SQL

Expected Query

Expected Output

Exercise 3

Medium

Write a query that uses FIRST_VALUE(amount) partitioned by user_id ordered by payment_date to return each user's first completed payment amount alongside every completed payment. Filter to user_id = 4. Return payment_idpayment_dateamount, and first_amount. Order by payment_date.

SQL

Expected Query

Expected Output

Exercise 4

Hard

Write a query that uses LAST_VALUE(plan) with ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING partitioned by user_id ordered by start_date to return each user's current (latest) plan, then groups by user_id to keep one row per user. Return user_id and current_plan. Order by user_id.

SQL

Expected Query

Expected Output