有关排序空值的处理方法

来源:互联网 发布:王欣认罪 知乎 编辑:程序博客网 时间:2024/05/28 11:29

以SQL Server为例,排序有Asc升序、Desc降序两种方式,默认Order By是以Asc正序;
当数据列Column中有空值时,排序会以空值最小优先;
如果要将Null排在后面,则:

select * from a Oder by case when id is null then 1 else 0 end,id;

如果要将Null排在前面,则:

select * from a order by case when id is null then 0 else 1 end , id desc;

在Oracle中可以使用Nulls First或者Nulls Last关键字来处理;
空值在前:

select * from a order by id nulls first;

空值在后:

select * from a order by id nulls last;