PostgreSQL ORDER BY Statement
In PostgreSQL,ORDER BYIt is used to arrange one or more columns of data in ascending (ASC) or descending (DESC) order.
Syntax
ORDER BYThe basic syntax of the clause is as follows:
SELECT column-list FROM table_name [WHERE condition] [ORDER BY column1, column2, .. columnN] [ASC | DESC];
You can use one or more columns in ORDER BY, but you must ensure that the columns to be sorted must exist.
ASCindicates ascending order,DESCindicates descending order.
Example
Create the COMPANY table (Download the COMPANY SQL file), with the data content as follows:
exampledb# select * from COMPANY; id | name | age | address | salary ----+-------+-----+-----------+-------- 1 | Paul | 32 | California| 20000 2 | Allen | 25 | Texas | 15000 3 | Teddy | 23 | Norway | 20000 4 | Mark | 25 | Rich-Mond | 65000 5 | David | 27 | Texas | 85000 6 | Kim | 22 | South-Hall| 45000 7 | James | 24 | Houston | 10000 (7 rows)
The following example will sort the results in ascending order based on the AGE field value:
exampledb=# SELECT * FROM COMPANY ORDER BY AGE ASC;
The following result is obtained:
id | name | age | address | salary ----+-------+-----+----------------------------------------------------+-------- 6 | Kim | 22 | South-Hall | 45000 3 | Teddy | 23 | Norway | 20000 7 | James | 24 | Houston | 10000 4 | Mark | 25 | Rich-Mond | 65000 2 | Allen | 25 | Texas | 15000 5 | David | 27 | Texas | 85000 1 | Paul | 32 | California | 20000 (7 rows)
The following example will sort the results in ascending order based on the NAME field value and the SALARY field value:
exampledb=# SELECT * FROM COMPANY ORDER BY NAME, SALARY ASC;
The following result is obtained:
id | name | age | address | salary ----+-------+-----+----------------------------------------------------+-------- 2 | Allen | 25 | Texas | 15000 5 | David | 27 | Texas | 85000 7 | James | 24 | Houston | 10000 6 | Kim | 22 | South-Hall | 45000 4 | Mark | 25 | Rich-Mond | 65000 1 | Paul | 32 | California | 20000 3 | Teddy | 23 | Norway | 20000 (7 rows)
The following example will sort the results in descending order based on the NAME field value:
exampledb=# SELECT * FROM COMPANY ORDER BY NAME DESC;
The following result is obtained:
id | name | age | address | salary ----+-------+-----+----------------------------------------------------+-------- 3 | Teddy | 23 | Norway | 20000 1 | Paul | 32 | California | 20000 4 | Mark | 25 | Rich-Mond | 65000 6 | Kim | 22 | South-Hall | 45000 7 | James | 24 | Houston | 10000 5 | David | 27 | Texas | 85000 2 | Allen | 25 | Texas | 15000 (7 rows)Other Extensions