The ORDER BY
clause specifies the order of rows in a query result set. Without
an ORDER BY
clause, the order of rows in a result set is not guaranteed.
A basic ORDER BY
clause orders results by one or more expressions:
SELECT name, population
FROM cities
ORDER BY population;
By default, results are sorted in ascending order. You can explicitly specify
the sort direction with ASC
(ascending) or DESC
(descending):
-- Ascending order (default)
SELECT name, population
FROM cities
ORDER BY population ASC;
-- Descending order
SELECT name, population
FROM cities
ORDER BY population DESC;
You can order by multiple columns, with each subsequent column used as a tiebreaker when the previous columns have equal values:
SELECT name, state_abbr, population
FROM cities
ORDER BY state_abbr, population DESC;
By default, NULL values are considered larger than any non-NULL value during sorting:
ASC
order, NULLs appear lastDESC
order, NULLs appear firstYou can override this behavior with NULLS FIRST
or NULLS LAST
:
-- Place NULL values first in ascending order
SELECT name, population
FROM cities
ORDER BY population ASC NULLS FIRST;
-- Place NULL values last in descending order
SELECT name, population
FROM cities
ORDER BY population DESC NULLS LAST;
You can also order by column position (1-based indexing) in the select list:
SELECT name, population
FROM cities
ORDER BY 2; -- Orders by the population column
Any expression can be used in the ORDER BY
clause:
SELECT name, population
FROM cities
ORDER BY population / 1000;
You can order by a column alias defined in the SELECT
clause:
SELECT name, population / 1000 AS thousands
FROM cities
ORDER BY thousands;