1. 程式人生 > >二十七、IN與EXISTS對SQL優化的影響

二十七、IN與EXISTS對SQL優化的影響

              IN與EXISTS對SQL優化的影響

select * from v$version;

drop table emp purge;
drop table dept purge;
create table emp as select * from scott.emp;
create table dept as select * from scott.dept;
set timing on 
set linesize 1000
set autotrace traceonly explain

--這三種寫法代價一樣
select * from dept where deptno NOT IN ( select deptno from emp ) ;
select * from dept where not exists ( select deptno from emp where emp.deptno=dept.deptno) ;
select * from dept where deptno NOT IN ( select deptno from emp where deptno is not null) and deptno is not null;

在ORACLE11g中,IN才用的是anti演算法,EXISTS才用的也是anti演算法,所以代價一樣。

在ORACLE10g中,IN才用的是anti演算法,EXISTS才用的filter演算法,所以代價不一樣。