Skip to main content

Chapter 3 · Sorting & Limiting

SQL ORDER BY and LIMIT Practice

ORDER BY puts results in a predictable order and LIMIT keeps only the first rows. Together they answer "top 5" and "most recent 10" questions, some of the most common requests an analyst gets.

The details matter: sorting by more than one column, choosing ASC or DESC for each, and deciding what happens when two rows tie.

Start practising26 exercises · 26 easy, 0 medium, 0 hard

Key ideas

ORDER BY col DESC
Sort high to low; ASC (the default) sorts low to high.
Multiple sort keys
ORDER BY state, city sorts by state, then by city inside each state.
LIMIT n
Return only the first n rows of the sorted result.
Ties
Add a second sort column (like id) so the "top 5" is always the same 5 rows.

Example: The five most expensive products

SELECT name, price
FROM products
ORDER BY price DESC
LIMIT 5;

Sort first, then cut: LIMIT always applies after ORDER BY.

In interviews

If the question says "top 3" and two products share third place, mention it. Knowing the difference between LIMIT and RANK() is a classic follow-up.

All 26 Sorting & Limiting exercises

Ordered from easiest to hardest. Each one runs on a real database with instant feedback.