SQL UNION ALL
UNION ALL combines the result sets of multiple SELECT statements and returns all rows including duplicates.
The UNION ALL operator is used to combine the results of two or more SELECT queries into a single result set without removing duplicate rows.
Rules for Using UNION ALL:
1️. All SELECT statements must have the same number of columns.
2️. The data types should be compatible.
3️. The column order must match.
Syntax
SELECT column1, column2 FROM table1 UNION ALL SELECT column1, column2 FROM table2;
Example: Query Using UNION ALL
SELECT CustomerName FROM CustomersIndia UNION ALL SELECT CustomerName FROM CustomersUSA;
Example:
SELECT CustomerID, CustomerName FROM CustomersIndia UNION ALL SELECT CustomerID, CustomerName FROM CustomersUSA;
Example: Combine OnlineOrders and StoreOrders
SELECT OrderID, ProductName FROM OnlineOrders UNION ALL SELECT OrderID, ProductName FROM StoreOrders; -- Shows all orders, even if some OrderIDs repeat.
Exam/Interview Definition:
UNION ALL in SQL Server is used to combine the results of multiple SELECT queries and returns all rows including duplicate records.