TopicsCheat sheetLessons
Lurndo › Topics › ORDER BY a, b

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
Result
start_timestageartist
15:00Forest StageSaffraan
16:30TentBas & Bram
17:00Forest StageJazzkwartet Mol
18:30TentMC Kade
20:00Main StageNina Vos
20:00TentBetonblok
22:00Main StageKiki Moreau
23:30TentNeon 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
Result
genrenamefee
electronicNeon Atlas32000
electronicDJ Okapi27500
electronicEcho Echo5000
folkThe Lighthouse Keepers9500
folkMarieke Staal4500
folkZonnebloem Collectief3000
folkaurora borealis2500
hip-hopMC Kade15000

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
Result
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
← PreviousSorting with ORDER BYNext →Removing duplicates with DISTINCT
SQL topicsCheat sheetExcelLeaderboardAccountPrivacyNederlands