Oracle排序中null值处理方法讲解

1、缺省处理

oracle在order by 时缺省认为null是最大值,所以如果是asc升序则排在最后,desc降序则排在最前

2、使用nvl函数

nvl函数可以将输入参数为空时转换为一特定值,如

nvl(employee_name,’张三’)表示当employee_name为空时则返回’张三’,如果不为空则返回employee_name

通过这个函数可以定制null的排序位置。

3、使用decode函数

decode函数比nvl函数更强大,同样它也可以将输入参数为空时转换为一特定值,如

decode(employee_name,null,’张三’, employee_name)表示当employee_name为空时则返回’张三’,如果不为空则返回employee_name

通过这个函数可以定制null的排序位置。

4、使用case 语法

case语法是oracle 9i后开始支持的,是一个比较灵活的语法,同样在排序中也可以应用

如:

select *

 from employee

 order by  (case employee_name

            when null then

             ‘张三’

            else

             employee_name

          end)

表示当employee_name为空时则返回’张三’,如果不为空则返回employee_name

通过case语法同样可以定制null的排序位置。

5、使用nulls first 或者nulls last 语法

nulls first和nulls last是oracle order by支持的语法

如果order by 中指定了表达式nulls first则表示null值的记录将排在最前(不管是asc 还是 desc)

如果order by 中指定了表达式nulls last则表示null值的记录将排在最后 (不管是asc 还是 desc)

使用语法如下:

–将nulls始终放在最前

select * from zl_cbqc order by cb_ld nulls first

–将nulls始终放在最后

select * from zl_cbqc order by cb_ld desc nulls last

(0)
上一篇 2022年3月22日
下一篇 2022年3月22日

相关推荐