ORDER BY
Sort the output rows. Runs after SELECT in logical order, so (unlike WHERE) it can reference column aliases and computed expressions. With LIMIT, ties at the cutoff boundary are broken non-deterministically unless you add a stable secondary sort.
Syntax #
sql
SELECT *
FROM table_name
ORDER BY col_1 DESC, col_2 ASC;Example #
Loading SQL editor...
Warning
ORDER BY + LIMIT without a tie-breaker is non-deterministic. If two rows tie on the sort key at the cutoff boundary, which one makes the top-N is engine- and plan-dependent, so reruns of the same report can return different rows. Always add a stable secondary sort (usually an id): ORDER BY revenue DESC, id.