ORDER BY
Without an explicit sort, the order rows come back in is not guaranteed — most databases return them in whatever order happens to be convenient internally.
ORDER BY lets you control the order of the result set precisely.ASC and DESC
Ascending (default) and descending order
SQL
SELECT first_name, last_name, salary FROM employees ORDER BY salary ASC; -- lowest to highest SELECT first_name, last_name, salary FROM employees ORDER BY salary DESC; -- highest to lowest
ASC is the default — if you omit both keywords, the database sorts ascending.Sorting by multiple columns
Listing more than one column sorts by the first column, and only uses later columns to break ties within groups of equal values in the earlier ones. Each column can have its own direction:
Sort by department, then salary within each department
SQL
SELECT first_name, last_name, department, salary FROM employees ORDER BY department ASC, salary DESC;
This groups employees alphabetically by department, and within each department, lists the highest earners first.
Sorting by column position
Some databases allow sorting by the numeric position of a column in the
SELECT list instead of its name:Sorting by position (works, but fragile)
SQL
SELECT first_name, last_name, salary FROM employees ORDER BY 3 DESC; -- sorts by the 3rd selected column: salary
Prefer column names over position numbers
Sorting by position is fragile — if someone later reorders, adds, or removes a column from the
SELECT list, the query silently starts sorting by a different column with no error at all. Using explicit column names in ORDER BY makes the intent clear and immune to that kind of accidental breakage.Where NULLs sort
NULL sort position varies by database
Different databases place
NULL values differently by default when sorting: PostgreSQL and Oracle sort NULL as the largest possible value by default (so it appears last in ASC order, first in DESC), while MySQL and SQL Server treat NULL as the smallest value (first in ASC, last in DESC). Most databases that support it let you control this explicitly with NULLS FIRST or NULLS LAST.Explicit NULL placement (PostgreSQL, Oracle)
SQL
SELECT first_name, phone_number FROM customers ORDER BY phone_number ASC NULLS LAST;
Sorting by an expression or alias
Because
ORDER BY runs after SELECT in the logical execution order, it can freely reference a column alias defined in the SELECT list, or repeat an expression directly:Sorting by an alias
SQL
SELECT product_name, price * quantity AS total FROM order_items ORDER BY total DESC;