AlgoMaster Logo

Exercise: Sorting and Pagination

Last Updated: May 10, 2026

1 min read

For this exercise, we will work with below data:

SQL

Exercise 1

Easy

Return the 3 shortest tracks from the tracks table. Show title and duration_seconds, sorted from shortest to longest.

SQL

Expected Query

Expected Output

Exercise 2

Easy

Return the 5 most recently signed up users. Show user_idusername, and signup_date, ordered from newest to oldest.

SQL

Expected Query

Expected Output

Exercise 3

Medium

Return page 2 of streams using OFFSET pagination with a page size of 5, sorted by stream_id ascending. Show stream_iduser_id, and started_at.

SQL

Expected Query

Expected Output

Exercise 4

Medium

For each track in the tracks table, compute its duration in minutes (as duration_seconds / 60.0) and return the 5 longest tracks. Show titleduration_seconds, and the computed duration_minutes aliased value, sorted by duration_minutes descending.

SQL

Expected Query

Expected Output

Exercise 5

Medium

Return artists sorted alphabetically by country, but place artists with a NULL country at the very end. Use a CASE expression so the query works on databases that do not support NULLS LAST. Show name and country.

SQL

Expected Query

Expected Output

Exercise 6

Hard

Write a query using keyset pagination that returns the next 5 streams after stream_id = 10, sorted ascending. Show stream_iduser_id, and started_at.

SQL

Expected Query

Expected Output

Exercise 7

Hard

Implement keyset pagination on the streams table sorted by started_at DESC, stream_id DESC. The previous page ended at started_at = '2024-03-03 14:00:00+00' and stream_id = 13. Return the next 5 rows. Show stream_iduser_id, and started_at.

SQL

Expected Query

Expected Output