Table of Contents
ToggleThe SQL UNION operator is used to combine the result sets of two or more SELECT statements. It ensures that the returned result set contains only unique values, making it highly useful for merging data from multiple tables.
SELECT statement must have the same number of columns.SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
By default, the UNION operator removes duplicate rows. To include duplicates, use UNION ALL.
SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;
Suppose we have two tables: Customers and Suppliers. Below is the Indian version of the data:
| CustomerID | CustomerName | City | Country |
|---|---|---|---|
| 1 | Raj Traders | Delhi | India |
| 2 | Patel Stores | Mumbai | India |
| SupplierID | SupplierName | City | Country |
|---|---|---|---|
| 1 | Sharma Supplies | Chennai | India |
| 2 | Gupta Exports | Delhi | India |
We can combine the cities from both tables using the following SQL query:
SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;
This query will return distinct city names:
