上QQ阅读APP看书,第一时间看更新
3.4.3 排序
使用排序子句可以对查询结果进行排序,排序子句是在SELECT语句后面加上“ORDER BY”子句,比如,想将查询结果按年龄排序,则查询语句如下:
osdba=# SELECT * FROM student ORDER BY age; no | student_name | age ----+--------------+----- 3 | 王明充 | 13 1 | 张三 | 15 2 | 李四 | 15 (3 rows)
排序子句“ORDER BY”应该在WHERE子句之后,如果顺序错了,执行时会报错:
osdba=# SELECT * FROM student ORDER BY age WHERE age >= 15; ERROR: syntax error at or near "WHERE" LINE 1: SELECT * FROM student ORDER BY age WHERE age >= 15;
把“ORDER BY”子句放到“WHERE”子句后面就不会报错了:
osdba=# SELECT * FROM student WHERE age >= 15 ORDER BY age; no | student_name | age ----+--------------+----- 1 | 张三 | 15 2 | 李四 | 15 (2 rows)
还可以按多个列对查询结果进行排序,比如,根据“age”和“student_name”两个列来排序:
osdba=# SELECT * FROM student ORDER BY age,student_name; no | student_name | age ----+--------------+----- 3 | 王明充 | 13 2 | 李四 | 15 1 | 张三 | 15 (3 rows)
也可以在排序子句的列名后加“DESC”进行倒序排序:
osdba=# SELECT * FROM student ORDER BY age DESC; no | student_name | age ----+--------------+----- 1 | 张三 | 15 2 | 李四 | 15 3 | 王明充 | 13 (3 rows) osdba=# SELECT * FROM student ORDER BY age DESC,student_name; no | student_name | age ----+--------------+----- 2 | 李四 | 15 1 | 张三 | 15 3 | 王明充 | 13 (3 rows)