Oracle 기초 : 실전(7) Set Operator

codePark·2020년 6월 17일
0

Oracle

목록 보기
11/23

Introduction: Set Operator

Set Operator는 Union의 상위 개념으로, 집합 연산의 결과를 열(Column)과 열(Column)간의 결합으로 표현하여 가상 테이블을 생성하는 것을 말한다.

Precondition of Set Operator

  1. 결합할 각 Table의 Column 수는 동일해야 한다.
  2. 대응하는 Column의 자료형간 상호 호환이 가능하여야 한다. (ex.char-varchar2)
  3. order by Clause는 마지막 결과 집합에 단 한번만 대입이 가능하다.

Types of Union


1. union: 합집합. 중복된 데이터는 제거하고 첫번째 Column을 기준으로 오름차순 정렬한다.
2. union all: 합집합. 단, 중복과 정렬에 무관하게 모든 데이터를 리턴한다.
3. intersect: 교집합의 값을 리턴한다.
4. minus: 차집합. 먼저 선언된 쿼리의 모든 값에서 이후에 선언된 쿼리의 산출값을 제한다.


Syntax: union/union all (Union Set)

Syntax of the union:
Query1
union
Query2
union(add'l)
Query3(add'l)
...

select emp_name, dept_code
from employee
union
select emp_id, emp_no
from employee

Syntax of the union all:
Query1
union all
Query2
union all(add'l)
Query3
...

select phone, email
from employee
union all
select job_code, dept_code
from employee

각 데이터의 대응/미대응 여부 및 쿼리의 선언 순서와 무관하게 같은 Result Set(결과 집합)을 리턴한다. (합집합의 결과를 리턴할 것이므로) 또한, 모든 구성 쿼리가 전제조건을 거스르지만 않는다면 갯수 제한 없이 여러개의 쿼리를 선언하고 결합할 수 있다.


Syntax: Intersect (Intersection Set)

Syntax of the intersect:
Query1
intersect
Query2
intersect(add'l)
Query3(add'l)

select emp_name, dept_code
from employee
intersect
select emp_id, emp_name
from employee

선언된 쿼리간 대응 데이터만을 리턴한다. (교집합)
따라서 각 쿼리의 선언 순서와 관계 없이 같은 결과 집합을 리턴한다.


Syntax: Minus (Relative Complement, Set Difference)

Syntax of the minus:
Query1
minus
Query2
minus(add'l)
Query3(add'l)

select emp_name, dept_code
from employee
minus
select emp_id, emp_name
from employee

먼저 선언된 쿼리의 "모든" 데이터에서 후위에 선언된 쿼리의 "모든" 데이터를 제한다. (차집합) 상기한 union/union all/intersect와 다르게 각 쿼리의 선언 순서가 매우 중요하며, 쿼리의 선언 순서가 달라지게 되면 도출될 결과 집합 또한 달라지게 된다.


Remark: Add Condition with Set Operator

Set Operator + Parentheses로 묶인 하나의 가상테이블에 공통의 조건문을 대입하거나 정렬을 적용하려는 경우에는 다음과 같은 문법으로 작성할 수 있다:
select Col1, Col2 ... (add'l)
from(
Query1
union/union all/intersect/minus
Query2
union/union all/intersect/minus(add'l)
Query3(add'l)
...
order by asc/desc(add'l)
)
where Conditions
group by Cols
having Conditions(add'l)
order by (add'l)

Remark: Add Conditions with diff.Cols

또한, Set Operator+Parentheses로 연합한 가상 테이블에 공통의 조건절을 대입할 때 각 Query의 컬럼명이 다른 경우 첫 번째 Query의 컬럼명을 전제로 조건문을 선언해야 정상적인 조건 대입 및 조회가 가능하다.


profile
아! 응애에요!

0개의 댓글