SQL course menu
SQL UNION: Combine Results From Multiple Queries
Learn how SQL UNION stacks the results of two or more SELECT statements, removes duplicates, and what rules the queries must follow. Includes INTERSECT and EXCEPT for comparing result sets.
On this page
A JOIN puts columns from two tables side by side. UNION does something different: it stacks the rows of two queries on top of each other into one result, and removes duplicates.
The example tables#
employees: name, city
customers: name, city
Syntax#
SELECT columns FROM table_a
UNION
SELECT columns FROM table_b;Example: every city we operate in#
SELECT city FROM employees
UNION
SELECT city FROM customers
ORDER BY city;city
---------
Bengaluru
Chennai
Delhi
Mumbai
PuneEmployees live in 4 cities and customers in 4 cities, but the combined list has 5, because UNION removed the cities that appear in both (and the repeated Mumbai).
The rules#
- Each
SELECTmust return the same number of columns. - Columns are matched by position, not by name, and must have compatible types.
- The column names in the result come from the first query.
ORDER BYgoes once, at the very end, and sorts the combined result.
Labelling where each row came from#
Add a constant column to each part:
SELECT name, 'Employee' AS type FROM employees WHERE city = 'Mumbai'
UNION
SELECT name, 'Customer' FROM customers WHERE city = 'Mumbai'
ORDER BY type, name;name | type
-----+---------
Asha | Customer
Asha | Employee
John | EmployeeAsha appears twice because the two rows are different (Customer vs Employee). UNION only removes rows that are identical in every column.
UNION vs UNION ALL#
UNION removes duplicates; UNION ALL keeps them. Removing duplicates means the database must sort or hash the combined result, so UNION ALL is faster. Use UNION only when you actually need duplicates removed.
UNION vs JOIN#
INTERSECT and EXCEPT#
Two related operators compare result sets:
-- Names that are both an employee and a customer
SELECT name FROM employees
INTERSECT
SELECT name FROM customers
ORDER BY name;name
-----
Asha
John
Meera
Ravi-- Employee names that are not customer names
SELECT name FROM employees
EXCEPT
SELECT name FROM customers;name
-----
PriyaINTERSECT and EXCEPT work in PostgreSQL, SQL Server, SQLite, and MySQL 8.0.31+. Oracle calls EXCEPT MINUS.
Common mistakes#
Practice#
Practice exercise
Produce one list of every distinct name that appears in either employees or customers, in alphabetical order. How many names does it contain?
Show hint
UNION of the two name columns, then ORDER BY name.
Show solution
SELECT name FROM employees
UNION
SELECT name FROM customers
ORDER BY name;name
-----
Asha
John
Meera
Priya
Ravi5 names. Four of them appear in both tables, but UNION keeps one copy of each.
Key takeaway#
Finished this lesson?