SQL UNION
UNION is used to combine the results of multiple SELECT statements into one result set while removing duplicate records.
The UNION operator is used to combine the results of two or more SELECT queries into a single result set.
It removes duplicate rows automatically.
Rules for Using UNION:
1️. The number of columns must be the same in all SELECT statements.
2️. The data types must be compatible.
3️. The column order must match.
Syntax
SELECT column1, column2 FROM table1 UNION SELECT column1, column2 FROM table2;
Example:
SELECT CustomerID, CustomerName FROM CustomersIndia UNION SELECT CustomerID, CustomerName FROM CustomersUSA;
Example: UNION with ORDER BY
SELECT CustomerName FROM CustomersIndia UNION SELECT CustomerName FROM CustomersUSA ORDER BY CustomerName;
Example: Combine online orders and store orders:
SELECT OrderID, ProductName FROM OnlineOrders UNION SELECT OrderID, ProductName FROM StoreOrders;
Interview Definition:
UNION in SQL Server combines the results of two or more SELECT queries into one result set and removes duplicate rows.