PostgreSQL ORDER BY Statement
In PostgreSQL,ORDER BY Used to sort data in one or more columns in ascending (ASC) or descending (DESC) order.
Syntax
ORDER BY The 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 exist.
ASC Indicates ascending order,DESC Indicates descending order.
Example
Create the COMPANY table (Download the COMPANY SQL file ), with the following data:
runoobdb# 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 sorts the results in ascending order by the AGE field value:
runoobdb=# 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 sorts the results in ascending order by the NAME field value and the SALARY field value:
runoobdb=# 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 sorts the results in descending order by the NAME field value:
runoobdb=# 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)