语法格式
ORDER [SIBLINGS] BY { column_name | number | expression } [ ASC | DESC ][ NULLS FIRST | NULLS LAST ] [ , ... ]
使用方法
ORDER BY语句默认按照升序对记录进行排序。如果希望按照降序对记录进行排序,请使用DESC关键字。
ORDER SIBLINGS BY指定兄弟节点之间用于排序的字段。
NULLS FIRST | NULLS LAST 关键字指定ORDER BY列中NULL值的排序位置,FIRST表示将NULL值排在最前面,LAST表示将NULL值排在最后面,若不指定该选项, ASC默认为NULLS LAST, DESC默认为NULLS FIRST。
示例
查询各部门中各工种的奖金信息,查询结果先按job升序排列,然后按section_name降序排列。
--删除表bonuses_depa1。
DROP TABLE IF EXISTS bonuses_depa1;
--创建表bonuses_depa1。
CREATE TABLE bonuses_depa1(section_id INT NOT NULL, section_name VARCHAR(50), staff_id INT NOT NULL, staff_name CHAR(50), job VARCHAR(30), bonus NUMBER);
--向表bonuses_depa1中INSERT数据。
INSERT INTO bonuses_depa1(section_id, section_name,staff_id, staff_name, job, bonus) VALUES(1,'devepment',23,'wangxia','developer',5000);
--向表bonuses_depa1中INSERT数据。
INSERT INTO bonuses_depa1(section_id, section_name,staff_id, staff_name, job, bonus) VALUES(2,'test',24,'limingying','tester',7000);
--向表bonuses_depa1中INSERT数据。
INSERT INTO bonuses_depa1(section_id, section_name,staff_id, staff_name, job, bonus) VALUES(3,'quality',25,'liulili','quality control',8000);
--向表bonuses_depa1中INSERT数据。
INSERT INTO bonuses_depa1(section_id, section_name,staff_id, staff_name, job, bonus) VALUES(2,'test',29,'liuxue','tester',8000);
--向表bonuses_depa1中INSERT数据。
INSERT INTO bonuses_depa1(section_id, section_name,staff_id, staff_name, job, bonus) VALUES(4,'products',21,'caoming','document developer',11000);
--提交。
COMMIT;
--查询各部门中各工种的奖金信息,查询结果先按job升序排列,然后按section_name降序排列。
SELECT section_name, job, bonus FROM bonuses_depa1 ORDER BY job, section_name DESC; SECTION_NAME JOB BONUS --------------- ------------------------------ ----------- devepment developer 5000 products document developer 11000 quality quality control 8000 test tester 7000 test tester 8000 5 rows fetched.