【SQL】含有NULL值的排序

时间:2022-05-25 15:32:38

查询结果中有NULL值,当进行升序排序时,NULL值默认为“最大值”,排在最后面。要想改变NULL值的显示顺序,只需要在SQL语句后面加上NULLS FIRST(排在前面),NULLS LAST(排在后面)。

例如:

1)升序排列,NUll值排在前面

SQL> SELECT DISTINCT department_id FROM employees ORDER BY 1 NULLS FIRST;

DEPARTMENT_ID

-------------

10

20

30

40

50

60

70

80

90

100

110

12 rows selected.

2)降序排列,NULL值排在后面

SQL> SELECT DISTINCT department_id FROM employees ORDER BY 1 DESC NULLS LAST;

DEPARTMENT_ID

-------------

110

100

90

80

70

60

50

40

30

20

10

12 rows selected.