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.
Controlling NULL placement
SELECT name, commission
FROM employees
ORDER BY commission DESC NULLS LAST;Exercise: PostgreSQL Order By
What is the default sort order when ORDER BY is used without specifying ASC or DESC?