[데이터베이스] 9. 집합

문정준's avatar
Feb 28, 2025
[데이터베이스] 9. 집합

1. 합집합 (Union all)

  • 결과를 합쳐서 제출
-- 집합 -- 1. 합집합 (Union All) select sum(sal), deptno from emp where deptno = 10 union all select sum(sal), deptno from emp where deptno = 20 union all select sum(sal), deptno from emp where deptno = 30;
notion image
  • 부서별 합계가 아닌 총합을 아래에 함께 표시하려면?
-- 총합 union all select sum(sal) from emp;
  • 그냥 붙이면 오류 발생
    • Column 수가 맞지 않음 : null 추가
-- 집합 -- 1. 합집합 (Union All) select sum(sal), deptno from emp where deptno = 10 union all select sum(sal), deptno from emp where deptno = 20 union all select sum(sal), deptno from emp where deptno = 30 -- 총합 union all select sum(sal), null from emp;
notion image
 
  • GROUP BY로 코드 간소화 가능
select sum(sal), deptno from emp group by deptno -- 총합 union all select sum(sal), null from emp;
  • 결과는 동일
 

2. 중복 제거한 합집합 (Union)

  • 결과를 합치되 중복되는 값은 제거
-- 2. Union (중복을 제거한 합집합 : 연산이 소요) -- union all select * from dept where deptno > 10 union all select * from dept where deptno < 30; -- union select * from dept where deptno > 10 union select * from dept where deptno < 30;
notion image
 

3. 교집합 (Intersect)

  • 두 결과 중 중복되는 값만 출력
-- 3. Intersect (교집합) select * from dept where deptno > 10 intersect select * from dept where deptno < 30;
notion image
 
 
 

4. 차집합 (Except)

  • 한 결과에서 다른 결과 값이 중복되는 것을 빼고 출력
-- 4. Except (차집합) select * from dept where deptno > 10 except select * from dept where deptno < 30;
notion image
Share article

sxias