AlgoMaster Logo

Exercise: ROW_NUMBER

Last Updated: May 12, 2026

1 min read

For this exercise, we will work with below data:

SQL

Exercise 1

Easy

For each stream by user_id 1, return stream_idstarted_at, and a row number rn ordered by started_at ASC. Order by started_at.

SQL

Expected Query

Expected Output

Exercise 2

Easy

Return every artist with their name and a row number rn assigned alphabetically by name. Order the result by rn.

SQL

Expected Query

Expected Output

Exercise 3

Medium

Find each user's most recent stream. Return user_idstream_id, and started_at. Use ROW_NUMBER with PARTITION BY user_id ORDER BY started_at DESC, stream_id DESC and keep only rn = 1. Order by user_id.

SQL

Expected Query

Expected Output

Exercise 4

Medium

For each user where user_id IN (1, 2, 3), return the first 2 streams (ordered by started_at). Show user_idstream_idstarted_at, and rn. Order by user_idrn.

SQL

Expected Query

Expected Output

Exercise 5

Hard

For each user where user_id IN (1, 2, 4), return the top 2 longest streams ordered by duration_listened DESC, with stream_id ASC as a tiebreaker. Show user_idstream_idduration_listened, and rn. Order by user_idrn.

SQL

Expected Query

Expected Output