在数据库世界中,NULL是一个标记,表示在记录时缺少数据或未知数据。当您对包含NULL的行进行排序时,您可以使用order by子句的NULLS FIRST或NULLS LAST选项来指定NULL与其他非空值的顺序:
ORDER BY sort_expresssion [ASC | DESC] [NULLS FIRST | NULLS LAST]
NULLS FIRST选项将NULL放在其他非空值之前,NULL LAST选项将NULL放在其他非空值之后
dvdrental=# -- create a new table
dvdrental=# CREATE TABLE sort_demo(num INT);
CREATE TABLE
dvdrental=#
dvdrental=# -- insert some data
dvdrental=# INSERT INTO sort_demo(num)
dvdrental-# VALUES
dvdrental-# (1),
dvdrental-# (2),
dvdrental-# (3),
dvdrental-# (null);
INSERT 0 4
dvdrental=# select num from sort_demo order by num;
num
-----
1
2
3
(4 rows)
dvdrental=# select num from sort_demo order by num nulls first;
num
-----
1
2
3
(4 rows)
#请注意,psql默认情况下将null显示为空字符串。为了使null更清晰,可以执行以下命令将空字符串更改为另一个空字符串,例如null
dvdrental=# \pset null null
Null display is "null".
dvdrental=# select num from sort_demo order by num nulls first;
num
------
null
1
2
3
(4 rows)
dvdrental=# select num from sort_demo order by num nulls last;
num
------
1
2
3
null
(4 rows)
#desc默认使用了nulls first
dvdrental=# select num from sort_demo order by num desc;
num
------
null
3
2
1
(4 rows)
#可以控制将null放置到最后,使用nulls last
dvdrental=# select num from sort_demo order by num desc nulls last;
num
------
3
2
1
null
(4 rows)