ORDER BY & LIMIT
Bring a little order
Lesson 5 of 20 · 6 min · Module 2: Ask precise questions
Sorting makes patterns visible. Find the most active learners by ordering their XP from highest to lowest.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Sort numerically in descending order
- Limit the number of result rows
- Distinguish top results from arbitrary rows
The idea
ORDER BY xp DESC sorts in descending order. ASC sorts ascending. LIMIT keeps only a given number of rows.
SELECT name, xp FROM learners
ORDER BY xp DESC
LIMIT 3;
01Sort before taking the first rows
ORDER BY xp DESC arranges learners by highest XP first. LIMIT 2 then keeps the first two result rows. LIMIT alone does not mean highest or best.
02Consider ties in a real report
If several rows share the same XP, an additional ordering expression such as name can make their presentation deterministic. This dataset’s top scores are distinct.
Your turn
name and xp for the two learners with the most XP, highest first.What the checks look for
- Returns Lee then Sam, with their XP
Take this with you
A top-N query needs both an ordering rule and a limit.