Filtering · Episode 3

Can we sort this?

ORDER BYASCDESCLIMIT
The story

Harry hands over a list of customers and signup dates. Hermione glances at it: “Can we sort this by signup date, newest first?”

Harry

Sort it how? The rows just come back in whatever order the table has them.

Hermione

Right — a table has no built-in order you should rely on. If you want an order, you ask for one.

The concept

ORDER BY sorts the result after everything else has run. By default it sorts ascending — smallest or earliest first.

What order should the rows come out in?

Build the query
query.sql
SELECT name, signup_date FROM customers
ORDER BY signup_date;
Result12 rows
namesignup_date
George Lee2022-11-19
Liam O'Connor2022-12-25
Alice Sharma2023-01-15
Diego Fernandez2023-01-30
Ivan Petrov2023-02-14
Bob Turner2023-02-20
Chloe Martin2023-03-05
Emma Wilson2023-04-11
Farah Khan2023-05-02
Hana Sato2023-06-08
Julia Souza2023-07-22
Kevin Zhang2023-08-01

That’s oldest first. Hermione wanted newest first, so flip it with DESC:

query.sql
SELECT name, signup_date FROM customers
ORDER BY signup_date DESC;

Hermione: “Perfect. Now just the 3 most recent.” Sorting gets you the right order — now cap how many rows come back with LIMIT:

query.sql
SELECT name, signup_date FROM customers
ORDER BY signup_date DESC
LIMIT 3;
Run it
query.sql

Running…

Try it: What if you sort by two columns — ORDER BY country ASC, signup_date DESC?
experiment.sql

Run your query to see results here.

SQL sorts by the first column, and only breaks ties using the second. Here every country only has 1–3 customers, so you get the countries in alphabetical order (Brazil, France, Germany…), and within each country, the newest signup comes first. Multi-column sorting is exactly this: a tiebreaker, applied left to right.

Your turn

The ops team wants the 5 earliest customers NOVA ever signed up — oldest first — just their name and signup date.

Opens in a new window, full width — come back here once you’re done.
Hint 1

You need the earliest rows, so think about which direction ORDER BY should sort in by default.

Hint 2

LIMIT controls how many rows come back, and it's applied after the sort.

Hint 3

SELECT name, signup_date FROM customers ORDER BY signup_date LIMIT 5;

Solution
solution.sql

Running…

Debrief

Ascending is the default, so “earliest first” needed no DESC at all — just ORDER BY signup_date, then a LIMIT to cap it at 5. ORDER BY and LIMIT are built to work together like this for almost any “top N” question — it’s a pattern you’ll reuse constantly.

One thing to remember

ORDER BY controls row order — ascending by default, DESC to flip it, and it can sort by more than one column. LIMIT caps how many rows come back, so together they answer “top N” questions.