1、问题
- 在 Oracle 中进行查询排序时,如果排序字段里面有空值的情况下,排序结果可能会达不到自己想要的结果。
- 例如:
select * from tableName order by vis desc
- 将SQL语句改写为:
select * from tableName order by vis desc nulls last
2、原因
- 在 order by 时,Oracle 认为缺省值 null 是最大值,因此
- 如果是 ASC 升序排列,则 null 值默认排在最后;
- 如果是 DESC 降序排列,则 null 值默认排在最前。
3、解决方案
- 从根源上避免这个问题,可以在建表时为该字段添加非空约束!
- 用 nvl 函数 或 decode 函数,将 null 值转换为特定值,一般是 0;
- 用 coalesce 函数,与 nvl 函数类似;
- 用 case when 语法,将 null 转换为一特定值(Oracle 9i 以后版本支持)
order by (case sortCol when null then ’0’ else sortCol end)
- 使用 nulls first 或者 nulls last(Oracle 专门用来 null 值排序的语法)
nulls first
:将 null 排在最前面。如:select * from tableName order by sortCol nulls first
nulls last
:将 null 排在最后面。如:select * from tableName order by sortCol nulls last
4、补充说明
- Oracle 认为缺省值 null 是最大值;SQLServer 认为 null 是最小值。
- 升序排列:null 值默认排在最前;
- 降序排列:null 值默认排在最后。
- 对于 SQLServer null值排序的处理,可以参考 Oracle 上述方法进行处理。