Can we sort this?
Harry hands over a list of customers and signup dates. Hermione glances at it: “Can we sort this by signup date, newest first?”
Sort it how? The rows just come back in whatever order the table has them.
Right — a table has no built-in order you should rely on. If you want an order, you ask for one.
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?
SELECT name, signup_date FROM customers
ORDER BY signup_date;| name | signup_date |
|---|---|
| George Lee | 2022-11-19 |
| Liam O'Connor | 2022-12-25 |
| Alice Sharma | 2023-01-15 |
| Diego Fernandez | 2023-01-30 |
| Ivan Petrov | 2023-02-14 |
| Bob Turner | 2023-02-20 |
| Chloe Martin | 2023-03-05 |
| Emma Wilson | 2023-04-11 |
| Farah Khan | 2023-05-02 |
| Hana Sato | 2023-06-08 |
| Julia Souza | 2023-07-22 |
| Kevin Zhang | 2023-08-01 |
That’s oldest first. Hermione wanted newest first, so flip it with DESC:
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:
SELECT name, signup_date FROM customers
ORDER BY signup_date DESC
LIMIT 3;Running…
Try it: What if you sort by two columns — ORDER BY country ASC, signup_date DESC?
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.
The ops team wants the 5 earliest customers NOVA ever signed up — oldest first — just their name and signup date.
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
Running…
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.
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.