ORDER BY
SELECT statement by one or more columns, expressions, or even the numeric position of a column in the select list. It always runs after filtering (WHERE) and grouping, and is typically the last thing applied before LIMIT/OFFSET.Basic sorting: ASC and DESC
ORDER BY clause can be sorted in ascending order (the default) or descending order. You can mix directions per column when sorting by more than one.Sort products by price, cheapest first
SELECT product_id, name, price FROM products ORDER BY price ASC; -- ASC is the default, so "ORDER BY price" is identical
Sort products by price, most expensive first
SELECT product_id, name, price FROM products ORDER BY price DESC;
Sorting by multiple columns
List several columns separated by commas. PostgreSQL sorts by the first column, and only uses later columns to break ties within groups of equal values in the earlier ones.
Newest orders first, then highest total for same-day orders
SELECT order_id, customer_id, order_date, total_amount FROM orders ORDER BY order_date DESC, total_amount DESC;
Here every order is grouped by date (most recent date first), and within a single date, orders with a larger total come first.
Controlling where NULLs land
Customers without a phone number listed last
SELECT customer_id, first_name, phone FROM customers ORDER BY phone ASC NULLS LAST;
Explicitly put NULLs first instead
SELECT customer_id, first_name, phone FROM customers ORDER BY phone ASC NULLS FIRST;
NULLS FIRST/NULLS LAST specified, is: ascending order sorts NULLs to the end, and descending order sorts NULLs to the start. This is a dialect-specific default worth memorizing, since MySQL and SQL Server behave differently by default.Sorting by expression or column position
You are not limited to sorting by a bare column name. Any expression computed from the row can be used, and as shorthand you can also refer to a column by its 1-based position in the select list.
Sort by a computed expression
SELECT name, price, price * 0.9 AS discounted_price FROM products ORDER BY price * 0.9 DESC;
Sort by column position (2nd column in the SELECT list)
SELECT name, price FROM products ORDER BY 2 DESC;
SELECT list, the sort silently changes meaning. Prefer naming columns explicitly in application code and views.Quick reference
Clause | Effect |
|---|---|
| Sort ascending (default) |
| Sort ascending, explicit |
| Sort descending |
| Sort by |
| Force NULLs to the top |
| Force NULLs to the bottom |
| Sort by the 2nd selected column |
ORDER BY runs after WHERE, GROUP BY, and HAVING, but before LIMIT/OFFSET
You can sort by columns that are not even in the SELECT list
Sorting on an indexed column can let PostgreSQL avoid an explicit sort step — see the indexes section later in this series