Learn SQL: ORDER BY a, b
Sorting on several columns
"The timetable for the poster," says Noor. "By day, and within each day by time. But some acts start at the same time, and then the order is different every time." Something can be done about that.
Equal values, no fixed order
On Saturday Nina Vos and Betonblok both start at 20:00. With only ORDER BY start_time the database doesn't know who goes first: that order is not fixed and may be different next time.
For a poster you want the same result every time. For that you add a second column.
SELECT start_time, stage, artist FROM performances WHERE day = '2025-07-19' ORDER BY start_time| start_time | stage | artist |
|---|---|---|
| 15:00 | Forest Stage | Saffraan |
| 16:30 | Tent | Bas & Bram |
| 17:00 | Forest Stage | Jazzkwartet Mol |
| 18:30 | Tent | MC Kade |
| 20:00 | Main Stage | Nina Vos |
| 20:00 | Tent | Betonblok |
| 22:00 | Main Stage | Kiki Moreau |
| 23:30 | Tent | Neon Atlas |
First one column, then the next
After ORDER BY you may list several columns, separated by commas. The database sorts on the first column; the second decides only when values in the first are equal.
Each column gets its own direction. Here the genres run from A to Z, and within each genre the most expensive artist comes first: DESC belongs only to fee.
SELECT genre, name, fee FROM artists ORDER BY genre, fee DESC| genre | name | fee |
|---|---|---|
| electronic | Neon Atlas | 32000 |
| electronic | DJ Okapi | 27500 |
| electronic | Echo Echo | 5000 |
| folk | The Lighthouse Keepers | 9500 |
| folk | Marieke Staal | 4500 |
| folk | Zonnebloem Collectief | 3000 |
| folk | aurora borealis | 2500 |
| hip-hop | MC Kade | 15000 |
Sorting text, with a trap
SQLite sorts text letter by letter, on the code of each character. In that code every capital comes before every lower-case letter: Z comes before a.
That's why *aurora borealis*, who deliberately writes her name in lower case, ends up at the very bottom, after Zonnebloem Collectief.
SELECT name FROM artists ORDER BY name| name |
|---|
| Bas & Bram |
| Betonblok |
| Brandwerk |
| DJ Okapi |
| Echo Echo |
| Jazzkwartet Mol |
| Kiki Moreau |
| Lotte & de Lampen |
Try it yourself
Make the timetable for Sunday 20 July. Show stage, start time and artist, by stage and within each stage by start time.
Ready for more?
The full lesson has 6 exercises, from easy to challenging, with hints, points and a streak you can build.
Start the lesson