PostgreSQL – ORDER BY Clause
The ORDER BY
clause is used in a SELECT
statement to sort the result set based on one or more columns. It allows you to specify the sorting order for the returned rows, which can be either ascending (ASC) or descending (DESC).
The basic syntax of the ORDER BY
clause is as follows:
SELECT column1, column2, ... FROM table_name WHERE condition ORDER BY column1 [ASC | DESC], column2 [ASC | DESC], ...;
Here’s what the different components of the ORDER BY
clause mean:
ORDER BY column1, column2, ...
: This specifies the columns by which you want to sort the result set. You can include one or more columns, separated by commas. The sorting is applied in the order you list the columns.ASC
: This keyword specifies ascending order (default). Rows are sorted from lowest to highest values for the specified columns.DESC
: This keyword specifies descending order. Rows are sorted from highest to lowest values for the specified columns.
Here’s an example of how you might use the ORDER BY
clause in a PostgreSQL query:
SELECT first_name, last_name, salary FROM employees WHERE department_id = 2 ORDER BY salary DESC, last_name ASC;
In this example, we’re retrieving the first name, last name, and salary of employees from department 2. The results are ordered first by salary in descending order and then by last name in ascending order.
You can use the ORDER BY
clause with numeric, character, date, and other types of columns to sort the result set based on your requirements.