시소당
exists구문을 사용하면 SQL성능이 증가되는 경우가 많다. 이는 해당건이 테이블에 있나 없나만을 체크하고 그 조건에 맞는 건만 수행하기 때문이다. and일 경우는 Where 구문의 다음에 나오며 or일 경우는 Where구문의 맨마지막에 사용한다.
Select … Select …
From dept D From dept D
Emp E Emp E
Where E.deptno = D.deptno Where E.deptno = D.deptno
And E.emp_type = ‘MANAGER’ And E.emp_type = ‘MANAGER’
And D.dept_cat = ‘A’; Or D.dept_cat = ‘A’;
<개선안>
Select … Select …
From emp E From emp E
Where exist ( Select ‘x’ Where E.emp_type = ‘MANAGER’
From dept Or exist ( Select ‘x’
Where deptno = E.deptno From dept
And deptcat = ‘A’) Where deptno = E.deptno
And E.emp_type = ‘MANAGER’; And deptcat = ‘A’)
Distinct를 사용하면 내부 소팅이 일어나 성능의 저하는 가져옴으로 exists구문을 사용한다.
Select distinct deptno, deptname
From dept d, emp e
Where d.deptno = e.deptno
<개선안>
Select deptno, deptname
From dept D
Where exists (select ‘x’ from emp E where E.deptno = D.deptno);
Not in대신에 Not exists를 사용하여 성능을 향상시킨다.
select … from emp
where deptno not in (select deptno from dept where dept_cat = ‘A’);
<개선안>
select … from emp
where not exists (select ‘x’ from dept where dept_cat = ‘A’);