oracle之is null和is not null的優化


oracle之優化is null語句

一:is null的優化

方法:通過nvl(字段,j)=j的方式,將字段中為空的數據轉化為j,從而正常使用索引。

具體實現條件則是:i is null <===> j = nvl(i,j);

注意:使用時必須要確保字段的數據不包含j,例如:(age,15)=15,此時有可能age

內容是15,此時不可以,j的值要變換,保證不再age的范圍之內。

函數介紹:

nvl(a,b,c.......):當a為空時取b,當b為空時取c,以此類推。

當然還有另外一種方式解決這個問題:將null包含到索引中

--使用nvl函數的方式(不用添加索引,推薦)
select * from student t where 1=nvl(t.age,1);
--當t.age不存在等於1的數據時等價於
--select * from student t where t.age is null;
--添加索引的方式
create index idx_age_x on tab_i(decode(age,null,1));
select * from student t where decode(t.age,null,1)=1;

二:is not null的優化

方法:結果集不包含j = nvl(i,j)即可

通常情況下使用not exists或者比較大小

示例:

1:not exists
select * from student t where not exists 
(select 1 form student s where 1=nvl(s.age,1));
--11g版本后not in和not exists趨於相似,也可以用not in
--當t.col_x不存在等於1的數據時等價於
--select * from student t where t.age is not null;
2:比較大小
--當t.age為總是大於1的數值時
select * from student t where 1<nvl(t.age,1);
--當t.age為總是小於1的數值時
select * from student t where 1>nvl(t.age,1);
--直接比較大小,暗含了 IS NOT NULL
select * from student t where t.age>1;
3:比較長度
--當t.age的長度總是大於1時
select * from student t where 2<=length(nvl(t.age,1));
--因為length函數的參數為空時,其結果為空,因而不能直接使用length函數

參考鏈接:

https://blog.csdn.net/qq_38880340/article/details/84290900


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM