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.
- 01Products in a Price RangeecommerceEasy
- 02Ten Most Recent OrdersecommerceEasy
- 03Orders by StatusecommerceEasy
- 04Budget-Friendly Products Under $10ecommerceEasy
- 05Customers Who Joined in 2024ecommerceEasy
- 06Pending and Processing OrdersecommerceEasy
- 07Accounts by TypefinanceEasy
- 08Ten Most Recent TransactionsfinanceEasy
- 09Closed Accounts with Remaining BalancefinanceEasy
- 10Savings Accounts with Balance Over 10000financeEasy
- 11List All Expired CardsfinanceEasy
- 12Large Deposits Over $5,000financeEasy
- 13Customers Born in the 1990sfinanceEasy
- 14Active Checking AccountsfinanceEasy
- 15Customers by Email DomainfinanceEasy
- 16List All Blocked CardsfinanceEasy
- 17Five Oldest Customer AccountsfinanceEasy
- 18Overdrawn AccountsfinanceEasy
- 19Credit Cards Ordered by Credit LimitfinanceEasy
- 20Doctors in a Salary RangehealthcareEasy
- 21Five Most Recent PatientshealthcareEasy
- 22Patients Without InsurancehealthcareEasy
- 23Prescriptions with High Refill CountshealthcareEasy
- 24Premium Insurance Plans with Low CopayhealthcareEasy
- 25Recent Abnormal Lab ResultshealthcareEasy
- 26Prescriptions with Zero RefillshealthcareEasy