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