SQL - UNION & UNION ALL
Overview
UNION removes duplicates across queries; UNION ALL preserves duplicates.
SELECT first_name AS name FROM employees
UNION
SELECT name FROM customers;
SELECT first_name AS name FROM employees
UNION
SELECT name FROM customers;
SELECT first_name AS name FROM employees
UNION
SELECT name FROM customers;
Prerequisite
Load the Standard Test Data.
Expected Output (live)
| name |
|---|
| Ada |
| Alice |
| Ben |
| Bob |
| Cara |
| Chen |
| Dan |
| Dee |
| Eli |
| Eva |
Sample Use Cases (2)
1) UNION ALL (Compare row counts)
| src | n |
|---|---|
| employees | 5 |
| customers | 5 |
2) Distinct cities across employees + customers
| city |
|---|
| Austin |
| Boston |
| New York |
| San Francisco |
| Seattle |