PostgreSQL ORDER BY clause
The PostgreSQL ORDER BY clause is used for sorting data in ascending or descending order. The data is sorted on the base on one or more columns.
column_list: It specifies the columns or calculations that you want to retrieve.
table_name: It specifies the tables that you want to retrieve records from. There must be at least one table listed in the FROM clause.
WHERE conditions: It is optional. It specifies that the condition must be fulfilled to retrieve records.
ASC: It is also optional. It sorts the result set in ascending order by expression (default, if no modifier is provider).
DESC: It is also optional. It sorts the result set in descending order by expression.
See this example:
Let's take a table "EMPLOYEES" having the following data.
ORDER BY: ASC
Execute the following query to retrieve the records ORDER BY AGE in ascending order:
ORDER BY: DESC
Execute the following query to retrieve the records ORDER BY NAME in descending order:
ORDER BY with multiple columns:
You can also fetch the records from table ORDER BY multiple columns.
Execute the following query to fetch the records from table "EMPLOYEES" ORDER BY NAME and ADDRESS in ascending order.