typestar

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

  1. DESC and ASC apply per key, not to the whole clause.
  2. NULLS LAST puts missing values at the end whichever way you sort.
  3. You can sort by an expression the SELECT list never returns.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Sorting & paging, step 7 of 23 in Language basics.

← Previous Next →