Subquery3: exists연산자, not exists연산자의 동작 원리를 이해하고 실제 프로젝트에 적용하기 위한 실무 가이드다.
* null값 해결법 => nvl()함수사용 또는 not null 연산자 사용을 적용할 수 있다.
exists연산자
서브쿼리의 결과 집합에 행이 존재하는 지 확인하는 연산자.
서브쿼리로부터 결과값이 존재(exist)하면 true를 반환.
서브쿼리로부터 결과값이 존재하지않으면 false를 반환.
상호관련서브쿼리임
1 2 3 4 5 6 7 8 9
//exists연산자 기본형 select 컬럼명, 컬럼명, 컬럼명 from 테이블명 where exists ( 서브쿼리 );
//not exists연산자 기본형 select 컬럼명, 컬럼명, 컬럼명 from 테이블명 where not exists ( 서브쿼리 );
exists연산자 예시 : employees테이블로 부터 자기 자신이 매니저인 사원의 employee_id, last_name, department_id 출력하는 쿼리
1 2 3 4 5 6 7 8 9 10 11 12 13 14
//exist사용 select employee_id, last_name, department_id from employees outer where exists (select 'x' from employees where manager_id = outer.employee_id);
//구상 select employee_id, last_name, department_id from employees where employee_id in (매니저아이디 리스트);
//서브쿼리사용 select employee_id, last_name, department_id from employees where employee_id in (select manager_id from employees);
//not exists사용 select department_id, department_name from departments d where not exists( select'dept in no one' from employees where department_id = d.department_id) order by department_id;
//구상 select d.department_id, d.department_name from departments d where (d.department_id not in (사원들이 있는 부서리스트));
//첫번째시도 select d.department_id, d.department_name from departments d where d.department_id not in (select e.department_id from employees e); //계속 no row인 경우는? null값때문!!! //근데 에러가 아닌 no row가 나오는 이유는? where는 조건절이기때문에 조건이 없다고해서 select구문이 에러가 나진않는다. //null값 해결법 => nvl사용
//두번째시도 : 서브쿼리 + not in을 이용해서 풀기 => 성공 select d.department_id, d.department_name from departments d where d.department_id not in (select nvl(e.department_id, 0) from employees e);
//강사님코드 select department_id, department_name from departments where department_id not in (select department_id from employees where department_id is not null) order by department_id;
no row인 경우는? null값때문!!!
근데 에러가 아닌 no row가 나오는 이유는? where는 조건절이기때문에 조건이 없다고해서 select구문이 에러가 나진않는다.
null값 해결법 => nvl()함수사용 또는 not null 연산자 사용
테이블 규모가 클때(500행이상)는 함수(nvl)보다 연산자(not null)이 성능이 더 좋다