SQL from Zero › Module 4: DQL: asking questions
Sorting and limiting
Put results in order and keep just the top few, like the three newest books.
Lesson 18 of 33 · about 12 minutes
Video: Top 3 in one lineThe narrated video for this lesson is coming soon. The lesson below covers the same ideas.
The lesson
Without instructions, a database returns rows in whatever order is quickest for it. When order matters, say so with ORDER BY.
SELECT title, price
FROM books
ORDER BY price;
- Sorting goes from smallest to largest (A to Z for text) by default. Add
DESCfor largest first:ORDER BY price DESC. - Sort by more than one column with commas.
ORDER BY country, namesorts by country, and by name within the same country.
Keep only the first few rows with LIMIT. It always goes last:
SELECT title, price
FROM books
ORDER BY price DESC
LIMIT 3;
That's "the three most expensive books". ORDER BY with LIMIT is how you answer any "top 5" or "latest 10" question.
The order of the parts is always the same: SELECT, FROM, then ORDER BY, then LIMIT.
Key ideas
- ORDER BY sorts results; add DESC to sort from largest to smallest.
- Use commas to sort by a second column when the first is the same.
- LIMIT keeps only the first rows, and it always comes last.
Practise
Loading practice…