-
关于 Oracle 中字段值为 NULL 时的排序顺序
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 firstnulls last:将 null 排在最后面。如:select * from tableName order by sortCol nulls last
4、补充说明
- Oracle 认为缺省值 null 是最大值;SQLServer 认为 null 是最小值。
- 升序排列:null 值默认排在最前;
- 降序排列:null 值默认排在最后。
- 对于 SQLServer null值排序的处理,可以参考 Oracle 上述方法进行处理。
-
相关阅读:
深入解析Spring Boot的常用注解和组件(下)
Windows内核--为什么C语言适合编写内核?(1.2)
数据结构与算法1-算法的特性
SecureCRT连接Amazon EC2 Linux AMI
回溯:组合、子集、排列 算法总结
鸿蒙应用开发之打包与上架
【20221130】【每日一题】用最少数量的箭引爆气球
机器学习笔记之线性分类——线性判别分析(二)模型参数求解过程
java中的泛型
华为OD机试:路灯照明问题(100分)
-
原文地址:https://blog.csdn.net/coder_lcw/article/details/125995972