UNION & UNION ALL

The SQL UNION Operator

UNION combines the result sets of two or more SELECT statements and removes duplicates. UNION ALL keeps duplicates and is faster.

SELECT column_name(s) FROM table1
UNION [ALL]
SELECT column_name(s) FROM table2;

UNION

Example

One contact list of customer cities and the employee departments (distinct values):

SELECT City AS Name, 'Customer city' AS Kind FROM Customers WHERE City IS NOT NULL
UNION
SELECT Department, 'Department' FROM Employees
ORDER BY Kind, Name;

Result: 9 rows

NameKind
BengaluruCustomer city
LondonCustomer city
MumbaiCustomer city
New YorkCustomer city
OsloCustomer city
TorontoCustomer city
FinanceDepartment
SalesDepartment
SupportDepartment

UNION ALL

Example

Countries of customers, twice: UNION ALL keeps every row:

SELECT Country FROM Customers WHERE Country = 'India'
UNION ALL
SELECT Country FROM Customers WHERE Country = 'India';

Result: 4 rows

Country
India
India
India
India