Skillversitas

UNION, INTERSECT & EXCEPT

UNION - Combining Query Results

UNION combines the results of two or more queries and removes duplicate rows.

SELECT name FROM OLD_EMPLOYEES
UNION
SELECT name FROM NEW_EMPLOYEES;

UNION ALL - All Rows

UNION ALL combines the results, including duplicate rows.

SELECT name FROM OLD_EMPLOYEES
UNION ALL
SELECT name FROM NEW_EMPLOYEES;
Operator Duplicates Description
UNION Removed Only unique rows
UNION ALL Kept All rows returned

INTERSECT - Data Intersection

INTERSECT returns the rows that appear in both queries.

SELECT name FROM ACTIVE_EMPLOYEES
INTERSECT
SELECT name FROM BONUS_EMPLOYEES;

EXCEPT / MINUS - Data Difference

EXCEPT returns the rows from the first query that are not present in the second query.

SELECT name FROM ALL_EMPLOYEES
EXCEPT
SELECT name FROM PROMOTED_EMPLOYEES;

Usage Rules

  1. The number of columns must be the same in all queries
  2. Column data types must be compatible
  3. Column order must match

Combination Example

SELECT name, department FROM EMPLOYEE_REGION_A
UNION
SELECT name, department FROM EMPLOYEE_REGION_B
ORDER BY department;

Important Tips

  • Use UNION ALL when duplicates are acceptable (it is faster)
  • ORDER BY can only be placed at the end
  • Keep column aliases consistent

Next, we will learn how to modify table structure with ALTER TABLE.