Skip to content

SQL UNION Operator

Syntax

The UNION operator in SQL is used to combine the results of two or more SELECT statements into a single result set, eliminating duplicate rows by default. To include duplicates, use UNION ALL.

-- Combine results and remove duplicates
SELECT column1, column2
FROM table1
UNION
SELECT column1, column2
FROM table2;
-- Combine results and include duplicates
SELECT column1, column2
FROM table1
UNION ALL
SELECT column1, column2
FROM table2;

Example

-- Combine employees from two departments
SELECT name, department
FROM department_a
UNION
SELECT name, department
FROM department_b;
/* Output (removes duplicates):
| name | department |
|-------------|-------------|
| John Doe | Sales |
| Jane Smith | Marketing |
| Alice Brown | HR |
*/
-- Combine employees and include duplicates
SELECT name, department
FROM department_a
UNION ALL
SELECT name, department
FROM department_b;
/* Output (includes duplicates):
| name | department |
|-------------|-------------|
| John Doe | Sales |
| John Doe | Sales |
| Jane Smith | Marketing |
| Alice Brown | HR |
*/