Oracle查詢優(yōu)化之is null和is not null優(yōu)化
最近工作的時候遇到了比較大的數(shù)據(jù)查詢,自己的sql在數(shù)據(jù)量小的時候沒問題,在數(shù)據(jù)量達到300W的時候特別慢,只有自己優(yōu)化sql了,以前沒有優(yōu)化過,所以記錄下來自己的優(yōu)化過程,本次是關于is null和is not null的優(yōu)化。所用環(huán)境0racle11g。
現(xiàn)有a表,a表中有字段b,我想查出a表中的b字段is null的數(shù)據(jù)。
- select * from a where b is null
我在b字段上建立的索引,但是當條件是is null 和is not null時,執(zhí)行計劃并不會走索引而是全表掃描。此時a表中的數(shù)據(jù)有310w條記錄,執(zhí)行這段查詢花費時間約為0.526秒
優(yōu)化:
通過函數(shù)索引:通過nvl(b,c)將為空的字段轉(zhuǎn)為不為空的c值,這里要確保數(shù)據(jù)中是不會出現(xiàn)c值的。再在函數(shù)nvl(b,c)上建立函數(shù)索引
- select * from a where nvl(b,c)=c
此時花費時間約為 0.01秒。
當條件為is not null 時同理可以用 nvl(b,c)<>c來代替
Oracle查詢優(yōu)化之子查詢條件優(yōu)化
環(huán)境:oracle 11g
現(xiàn)有a表與b表通過a01字段關聯(lián),要查詢出a表的數(shù)據(jù)在b表沒有數(shù)據(jù)的數(shù)據(jù);sql如下
- select count(1) from (select a.*,(select count(1) from b where b.a01=a.a01) as flag from a) where flag=0
因為flag是虛擬字段沒有走不了索引導致這條sql執(zhí)行起來特別慢 310W條數(shù)據(jù)查總數(shù)花費2秒左右。
利用not exists優(yōu)化sql如下
- select count(1) from a where not exists(select 1 from b where a.a01=b.b01)
利用not exists走索引,執(zhí)行花費時間大約為0.2秒