ORDER BY is the final logical step of a SELECT statement. After rows are filtered, grouped, and projected, ORDER BY arranges the resulting set according to the specified columns or expressions. If multiple sort keys are listed, the second key is applied when preceding keys compare as equal, and so on. The default direction is ASC (ascending). DESC reverses the order. Numeric positions can reference output columns, but explicit column names are clearer and safer. NULLS FIRST and NULLS LAST, supported in many dialects, control null ordering when direction alone is insufficient. Because ORDER BY forces the database to compare every returned row, it can add significant cost, especially without supporting indexes. Some databases require ORDER BY columns to appear in the SELECT list unless DISTINCT or UNION is used; Standard SQL does not. When combined with LIMIT/OFFSET (or FETCH FIRST), ORDER BY enables robust pagination.
sort_key
(column or expression) - Required. One or more columns or expressions that define the sort order.ASC
(keyword) - Optional. Sorts in ascending order (lowest to highest). Default.DESC
(keyword) - Optional. Sorts in descending order (highest to lowest).NULLS FIRST / NULLS LAST
- Optional. Specifies where NULL values appear in the ordering. Support varies.GROUP BY, LIMIT, FETCH FIRST, DISTINCT, UNION, WINDOW FUNCTIONS, INDEXES
ANSI SQL-86
No. Without an ORDER BY clause, row order is undefined and can change between runs.
Use NULLS LAST if your database supports it: `ORDER BY column ASC NULLS LAST`. In MySQL, add `ORDER BY column IS NULL, column`.
After SELECT, FROM, WHERE, GROUP BY, and HAVING have produced the final set, ORDER BY sorts that set for output.
Yes, `ORDER BY 1` refers to the first SELECT column, but explicit names are clearer and safer.