SELECT select_list
FROM table
WHERE expr operator
(SELECT select_list
FROM table);
select last_name, job_id, salary
from employees
where salary = (salary Min(salary)
from employees);
select department_id, MIN(salary)
from employees
group by department_id
having MIN(salary) > (select MIN(salary)
from employees
where department_id = 50);
// salary에 null값이 있는 테이블의 경우
select employee_id, last_name, salary
from employees
where salary >= (select avg(nvl(salary,0))
from employees)
order by salary;
🔷 단일행 서브쿼리
🔷 다중행 서브쿼리
🔷 단일컬럼 서브쿼리
🔷 다중컬럼 서브쿼리
서브쿼리로부터 단일행이 반환되는 유형
메인쿼리에 단일행 비교연산자 사용
❌ 잘못된 예제
⭕ 올바른 예제
select last_name, job_id, salary
from employees
where job_id = (select job_id
from employees
where last_name = 'Bell')
and salary > (select salary
from employees
where last_name = 'Bell');
❌ 잘못된 예제
⭕ 올바른 예제
select employee_id, last_name
from employees
where salary in (select min(salary)
from employees
group by department_id);
select last_name, job_id
from employees
where job_id = (select job_id
from employees
where last_name = 'Haas');
서브쿼리로부터 다중행이 반환되는 유형
메인쿼리에 다중행 비교연산자 사용
// <any : 최대값보다 작은지를 비교하는 연산자
select employee_id, last_name, job_id, salary
from employees
where salary <any(select salary
from employees
where job_id = 'IT_PROG')
and job_id <> 'IT_PROG';
// < all : 최소값보다 작은지를 비교하는 연산자
select employee_id, last_name, job_id, salary
from employees
where salary <all (select salary
from employees
where job_id = 'IT_PROG')
and job_id <> 'IT_PROG';
select emp.last_name
from employees emp
where emp.employee_id <> all
(select mgr.manager_id
from employees mgr
where manager_id is not null);
서브쿼리로부터 하나의 컬럼을 기준으로 값이 반환되는 유형
비쌍 비교 방식 사용
서브쿼리로부터 여러 컬럼을 기준으로 값이 반환되는 유형
쌍 비교 방식 사용하기 (좌변과 우변의 컬럼 개수 일치해야 함)
<연습문제>
employees 테이블로부터 last_name에 "u"가 포함된 사원과 같은 부서에 근무하는 모든 사원의 employee_id와 last_name을 출력하는 구문을 작성하시오.
employees 테이블로부터 평균보다 많은 급여를 받고 성에 "u"가 포함된 사원이 있는 부서에서 근무하는 모든 사원의 employee_id, last_name 및 salary를 출력하는 구문을 작성하시오