UNION
The UNION operator combines the results of two or more SELECT queries into a single result set, stacking their rows together - unlike a join, which combines columns side by side.
Basic Syntax
SELECT first_name, city FROM customers
UNION
SELECT first_name, city FROM archived_customers;
Rules for Using UNION
- Each SELECT statement must return the same number of columns
- Corresponding columns must have compatible data types
- Column names in the final result come from the first SELECT statement
UNION vs UNION ALL
UNION automatically removes duplicate rows from the combined result, while UNION ALL keeps every row, including duplicates - and is faster since it skips the extra de-duplication step.
-- Keeps duplicates, faster
SELECT first_name FROM customers
UNION ALL
SELECT first_name FROM archived_customers;
You've Completed This Section
This wraps up SQL joins and combining queries - from writing subqueries and understanding why joins exist, through every join type (Cross, Inner, Self, Left, Right, Full Outer), to stacking result sets together with UNION. Together, these techniques let you pull related data together from across an entire relational database.