The UNION operator is used to combine the result-set of two or more SELECT statements.
SELECT statement within UNION must have the same number of columns.SELECT statement must also be in the same order.UNION SyntaxSELECT column_name(s) FROM table1 UNION SELECT column_name(s) FROM table2;
By default, the UNION operator selects only distinct (unique) values. If you want to allow duplicate values, use UNION ALL.
Customers Table:
| CustomerID | CustomerName | Country |
|---|---|---|
| 1 | Alfreds Futterkiste | Germany |
| 2 | Ana Trujillo Emparedados | Mexico |
Suppliers Table:
| SupplierID | SupplierName | Country |
|---|---|---|
| 1 | Exotic Liquids | UK |
| 2 | New Orleans Cajun Delights | USA |
| 3 | Grandma Kelly's Homestead | USA |
UNION ExampleThe following SQL statement returns the cities (only distinct values) from both the "Customers" and the "Suppliers" table.
SELECT City FROM Customers UNION SELECT City FROM Suppliers ORDER BY City;
UNION with WHEREThe following SQL statement returns the German cities (only distinct values) from both the "Customers" and the "Suppliers" table.
SELECT City, Country FROM Customers WHERE Country = 'Germany' UNION SELECT City, Country FROM Suppliers WHERE Country = 'Germany' ORDER BY City;