PostgreSQL Order By

The ORDER BY clause controls the order in which a query's rows are returned.

Sorting Query Results

Without ORDER BY, PostgreSQL is free to return rows in whatever order is most efficient for the current query plan, which can vary between runs. ORDER BY guarantees a specific order by sorting on one or more columns, ascending by default or descending with the DESC keyword.

Sorting ascending and descending

SELECT name, salary
FROM employees
ORDER BY salary DESC;

Sorting by Multiple Columns

You can list several sort keys separated by commas. PostgreSQL sorts by the first column, and only uses later columns to break ties among rows that share the same value in earlier columns. Each column can independently specify ASC or DESC.

A primary sort key with a tiebreaker

SELECT name, department, salary
FROM employees
ORDER BY department ASC, salary DESC;

Sorting by Expression or Position

ORDER BY accepts computed expressions, not just column names, and PostgreSQL also lets you reference a column by its position in the SELECT list. NULL values need special handling: by default PostgreSQL sorts NULLs as larger than any other value in ascending order, which you can override with NULLS FIRST or NULLS LAST.

ClauseBehavior
ORDER BY colAscending (ASC is implied)
ORDER BY col DESCDescending
ORDER BY col NULLS LASTNULLs sorted after all other values
ORDER BY 2Sorts by the second column in the SELECT list

Controlling NULL placement

SELECT name, commission
FROM employees
ORDER BY commission DESC NULLS LAST;
Note: Sorting by column position (ORDER BY 1, 2) is convenient in ad hoc queries, but prefer explicit column names in application code so the query survives a reordered SELECT list.
Note: An ORDER BY on an unindexed column requires PostgreSQL to sort the full result set at query time. On large tables, an index on that column can turn the sort into a much cheaper index scan.

Exercise: PostgreSQL Order By

What is the default sort order when ORDER BY is used without specifying ASC or DESC?