Lessons · SQL · ORDER BY two columns
Sorting by more than one thing
ORDER BY a DESC, b ASC sorts by a descending and breaks ties by b ascending.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Leaderboards and listings need a deterministic order or the same row moves between pages.
How to think about it
What breaks the tie? Primary sort first, then the tiebreak. Add a unique column last so the order is stable.
Worked example
SELECT title, year FROM filmsThe columns; the order comes next.
ORDER BY year DESC, title ASC;Newest first; same year alphabetical.
Your turn
Highest score first, ties by name.
ORDER BY score , name
Run a query against real tables
The trap
Assuming ASC when omitting a direction on the second column after a DESC on the first. It is per column.
Practise ORDER BY two columns on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.