Oracle 排序中常用的NULL值处理方法

1、在oracle中 null 缺省会认为是最大值 ,因此
select id,description from security_application where mod(id,4)=0 order by description

执行结果:

[img]http://dl.iteye.com/upload/attachment/211181/c7332605-f467-396e-b312-338a9245701c.png[/img]

select id,description from security_application where mod(id,4)=0 order by description desc

执行结果:

[img]http://dl.iteye.com/upload/attachment/211185/3734e5ea-0193-3fd6-b747-723a1f13415b.png[/img]

2、使用nvl函数 nvl函数可以将输入参数为空时转换为一特定值,如nvl(description,'...')表示当description为空时则返回'...’,如果不为空则返回description通过这个函数可以定制null的排序位置。
select id,nvl(description,'...') from security_application where mod(id,4)=0 order by description desc


3、使用decode函数 decode函数比nvl函数更强大,同样它也可以将输入参数为空时转换为一特定值,如
select id,decode(description,null,'...', description) from security_application where mod(id,4)=0 order by description desc
表示当description为空时则返回’...’,如果不为空则返回description通过这个函数可以定制null的排序位置。

4、使用case 语法 Case语法是Oracle 9i后开始支持的,是一个比较灵活的语法,同样在排序中也可以应用如:
select id,description from security_application where mod(id,4)=0 order by (case description when null then '...' else description end) desc

表示当description 为空时则返回’...’,如果不为空则返回description 通过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 id,description from security_application where mod(id,4)=0 order by description desc nulls first


--将nulls始终放在最后:
select id,description from security_application where mod(id,4)=0 order by description desc nulls last


6、NVL (expr1, expr2)
expr1为NULL,返回expr2;expr1不为NULL,返回expr1。注意两者的类型要一致
NULL指的是空值,或者非法值。

7、NVL2 (expr1, expr2, expr3)
expr1不为NULL,返回expr2;expr1为NULL,返回expr3。expr2和expr3类型不同的话,expr3会转换为expr2的类型

8、NULLIF (expr1, expr2)
相等返回NULL,不等返回expr1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值