Chapter 12-2 Set Operators
Chapter 12-2 Set Operators
• Set Operators
– Combine the results of two or more SELECT statements
• UNION
• UNION ALL
• INTERSECT
• MINUS
1
Tables for Set Operators
2
UNION Operator
3
UNION ALL Operator
4
INTERSECT Operator
5
MINUS Operator
6
Tables for Set Operators
SELECT * FROM s_employees;
7
UNION Operator
• The UNION operator returns all rows from both
tables, after eliminating duplicates
8
UNION Operator
SELECT employee_id, first_name, last_name, department_id
FROM s_employees
UNION
SELECT employee_id, first_name, last_name, dept_id
FROM s_employees_retired;
9
Set Operator Rules
• The number of columns and the data types of the
columns must be identical in all of the SELECT
statements used in the query
• The names of the columns need not be identical
• Column names in the output are taken from the
column names in the first SELECT statement
– So any column aliases should be entered in the first
statement as you would want to see them in the finished
report
10
UNION Operator
SELECT employee_id, first_name
FROM s_employees
UNION
SELECT employee_id, first_name, last_name
FROM s_employees_retired;
11
UNION ALL Operator
• The UNION ALL operator returns all rows from both
tables, without eliminating duplicates
12
UNION ALL Operator
SELECT employee_id, first_name, last_name, department_id
FROM s_employees
UNION ALL
SELECT employee_id, first_name, last_name, dept_id
FROM s_employees_retired
ORDER BY employee_id;
13
INTERSECT Operator
• The INTERSECT operator returns all rows common
to both tables
14
INTERSECT Operator
SELECT employee_id, first_name, last_name, department_id
FROM s_employees
INTERSECT
SELECT employee_id, first_name, last_name, dept_id
FROM s_employees_retired
ORDER BY employee_id;
15
MINUS Operator
• The MINUS operator returns all rows found in one
table but not the other
16
Tables for Set Operators
SELECT * FROM s_employees;
17
MINUS Operator 1/2
SELECT employee_id, first_name, last_name, department_id
FROM s_employees
MINUS
SELECT employee_id, first_name, last_name, dept_id
FROM s_employees_retired
ORDER BY employee_id;
18
MINUS Operator 2/2
SELECT employee_id, first_name, last_name, dept_id
FROM s_employees_retired
MINUS
SELECT employee_id, first_name, last_name, department_id
FROM s_employees
ORDER BY employee_id;
19