Sorting on several keys in SQL
Each sort key breaks ties in the one before it.
SELECT
name,
country,
score
FROM players
ORDER BY
country ASC,
score DESC,
LENGTH(name) ASC,
name NULLS LAST;
How it works
DESCandASCapply per key, not to the whole clause.NULLS LASTputs missing values at the end whichever way you sort.- You can sort by an expression the SELECT list never returns.
Keywords and builtins used here
ASCBYDESCFROMLASTLENGTHORDERSELECT
The run, in numbers
- Lines
- 10
- Characters to type
- 109
- Tokens
- 26
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 21 seconds.
Step 2 of 3 in Sorting & paging, step 7 of 23 in Language basics.