lesson 08 Filtering & sorting · beginner
Sort & limit
Order your results and choose how many rows to return.
the idea
ORDER BY sorts the output; ASC is ascending and DESC descending. LIMIT keeps a number of rows after sorting. Use a secondary key when ties need deterministic ordering.
tables in this lesson
The challenges use this data. Each column shows its type underneath; → marks a link to another table.
products4 columns · 6 rows
| idinteger · key | nametext | categorytext | pricereal |
|---|---|---|---|
| 1 | Notebook | Stationery | 12 |
| 2 | Desk lamp | Home | 45 |
| 3 | Keyboard | Tech | 80 |
| 4 | Pen set | Stationery | 8 |
| 5 | Headphones | Tech | 120 |
showing 5 of 6 rows
example
The idea in one query. Press Run to see what it returns; running examples never affects your progress.
SELECT name, price FROM products ORDER BY price DESC, name ASC LIMIT 3;
Watch for: LIMIT without ORDER BY does not promise which rows you get.
build it step by step
Each step changes one thing. Run them in order and watch the result change.
Sort prices before cutting. ORDER BY decides which rows come first. LIMIT only makes sense after the sort, or you get an arbitrary cut.
step-1.sqlSELECT name, price FROM products ORDER BY price DESC, name ASC;
Keep the top of the sorted list. DESC puts expensive products first. LIMIT 3 keeps only the first three after sorting.
step-2.sqlSELECT name, price FROM products ORDER BY price DESC, name ASC LIMIT 3;