In this PostgreSQL post explains how to use the PostgreSQL ORDER BY clause with syntax and examples.
The PostgreSQL ORDER BY clause is used to sort the records in your result set. The ORDER BY clause can only be used in SELECT statements.
The syntax for the ORDER BY clause in PostgreSQL is:
The columns or calculations that you wish to retrieve.
The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause.
Optional. The conditions that must be met for the records to be selected.
Optional. It sorts the result set in ascending order by expression (default, if no modifier is provider).
Optional. It sorts the result set in descending order by expression.
Optional. If specified, all NULL values sort before non-NULL values in the result set.
Optional. If specified, all NULL values sort after non-NULL values in the result set.
The PostgreSQL ORDER BY clause can be used without specifying the ASC or DESC modifier. When this attribute is omitted from the ORDER BY clause, the sort order is defaulted to ASC or ascending order.
For example:
This PostgreSQL ORDER BY example would return all records sorted by the last_name field in ascending order and would be equivalent to the following ORDER BY clause:
Most programmers omit the ASC attribute if sorting in ascending order.
When sorting your result set in descending order, you use the DESC attribute in your ORDER BY clause as follows:
This PostgreSQL ORDER BY example would return all records sorted by the last_name field in descending order.
You can also use the PostgreSQL ORDER BY clause to sort by relative position (ordinal position) in the result set, where the first field in the result set is 1. The next field is 2, and so on.
For example:
This PostgreSQL ORDER BY would return all records sorted by the city field in descending order, since the city field is in position #3 in the result set and would be equivalent to the following ORDER BY clause:
When sorting your result set using the PostgreSQL ORDER BY clause, you can use the ASC and DESC attributes in a single SELECT statement.
For example:
This PostgreSQL ORDER BY would return all records sorted by the last_name field in ascending order, with a secondary sort by first_name in descending order.