SQL UNION
SQL UNION is a type of operator in Structured Query Language (SQL) used to combine the results of two or more SELECT statements into a single result set. The UNION operator eliminates duplicate rows from the combined results, and it returns the unique values from all SELECT statements.
Orders Table:
OrderID | CustomerID |
---|---|
1 | 10 |
2 | 20 |
3 | 30 |
Customers Table:
CustomerID | CustomerName |
---|---|
20 | Alice |
30 | Bob |
40 | Charlie |
Suppose we want to retrieve the CustomerID and CustomerName from both the Orders and Customers tables and combine the results into a single result set. In that case, we can use the UNION operator to combine the SELECT statements from both tables as follows:
1SELECT CustomerID, CustomerName 2FROM Orders 3UNION 4SELECT CustomerID, CustomerName 5FROM Customers;
The output of the above query will be:
CustomerID | CustomerName |
---|---|
10 | NULL |
20 | Alice |
30 | Bob |
40 | Charlie |
As we can see from the output, the UNION operator returns the unique values from both SELECT statements. The result contains only one row for each customer, even though there are duplicate CustomerID values in both tables.