In PostgreSQL ORDER BY Used to sort one or more columns of data in ascending (ASC) or descending (DESC) order. ORDER BY The basic syntax of the clause is as follows: You can use one or more columns in ORDER BY, but you must make sure that the columns you want to sort must exist. ASC Indicates ascending order DESC Indicates descending order. Create the COMPANY table ( 下载 COMPANY SQL 文件 ), the data are as follows: The following example will determine the results based on the The following results are obtained: The following example will determine the results based on the The following results are obtained: The following example will determine the results based on the The following results are obtained: 5.23.1. Grammar ¶
SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
5.23.2. Example ¶
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)
AGE
Field values are sorted in ascending order:runoobdb=# SELECT * FROM COMPANY ORDER BY AGE ASC;
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)
NAME
Field values and
SALARY
Sort the field values in ascending order:runoobdb=# SELECT * FROM COMPANY ORDER BY NAME, SALARY ASC;
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)
NAME
Field values are sorted in descending order:runoobdb=# SELECT * FROM COMPANY ORDER BY NAME DESC;
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)