English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In PostgreSQL,ORDER BY Used to sort one or more columns in ascending (ASC) or descending (DESC) order.
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.
Create COMPANY table (Download COMPANY SQL file ),Data content as follows:
w3codeboxdb# 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 according to the AGE field value:
w3codeboxdb=# SELECT * FROM COMPANY ORDER BY AGE ASC;
The following results are 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 according to the NAME field value and the SALARY field value:
w3codeboxdb=# SELECT * FROM COMPANY ORDER BY NAME, SALARY ASC;
The following results are 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 according to the NAME field value:
w3codeboxdb=# SELECT * FROM COMPANY ORDER BY NAME DESC;
The following results are 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)