SQL

[SQL][TIL] Not-IN 연산자 (null값 주의하자)

breadz 2021. 7. 8. 10:49

※ Not-IN 연산자는 null값을 처리해줘야 결과를 출력할 수 있다!!

Q_ 부하직원이 없는 사원들의 정보를 출력하시오! (mgr에 해당하지 않는 직원, 후임이 없는 직원)

select *
from emp
where empno not in (select mgr
                    from emp);
select *
from emp
where empno != 7839
   and empno != 7566
   and empno != (null)           
   and empno != 7698;

// mgr 컬럼의 null 값 때문에 출력이 안 됨. null값은 비교연산을 할 수 없다. 왜? ☆아직☆ 정해지지 않은 값이기 때문에


방법1) nvl 함수 이용

select *
from emp
where empno not in (select nvl(mgr,-1)
                    from emp);

방법2) is not null 문법 이용

select *
from emp
where empno not in (select mgr
                    from emp
                    where mgr is not null);