Careeroza
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
| Name | Kind |
|---|---|
| Bengaluru | Customer city |
| London | Customer city |
| Mumbai | Customer city |
| New York | Customer city |
| Oslo | Customer city |
| Toronto | Customer city |
| Finance | Department |
| Sales | Department |
| Support | Department |
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 |