UNION Operations
UNION Operations
Section titled βUNION OperationsβWhat it means
Section titled βWhat it meansβUNION combines the results of two or more SELECT queries into a single result set, stacked vertically. Every query in a UNION must return the same number of columns, in compatible data types. UNION removes duplicate rows across the combined results by default; UNION ALL keeps every row, including duplicates, and is faster since it skips the deduplication step.
Examples
Section titled βExamplesβ-- Combine active and archived customers into one resultSELECT Name, Email FROM CustomersUNIONSELECT Name, Email FROM ArchivedCustomers;
-- UNION ALL keeps duplicates, and is faster (no dedup work)SELECT Name, Email FROM CustomersUNION ALLSELECT Name, Email FROM ArchivedCustomers;
-- Column names in the output come from the FIRST querySELECT Name AS ContactName, Email FROM CustomersUNIONSELECT Name, Email FROM Suppliers; -- still shows as "ContactName" in results
-- Adding a literal to distinguish the source of each rowSELECT Name, 'Customer' AS SourceType FROM CustomersUNION ALLSELECT Name, 'Supplier' AS SourceType FROM Suppliers;Common mistake
Section titled βCommon mistakeβUsing UNION when you actually want UNION ALL (or vice versa) β UNIONβs automatic deduplication requires SQL Server to sort/compare every row across both result sets, which is noticeably slower on large data sets and unnecessary if you already know there are no duplicates (or donβt care about them).
-- Unnecessarily slow if duplicates are impossible or don't matterSELECT Name FROM CustomersUNIONSELECT Name FROM Suppliers;
-- Faster when you don't need deduplicationSELECT Name FROM CustomersUNION ALLSELECT Name FROM Suppliers;Quick practice
Section titled βQuick practiceβ-
Whatβs the difference between
UNIONandUNION ALL?Answer
UNIONremoves duplicate rows from the combined result;UNION ALLkeeps every row, including duplicates, and is faster since it skips deduplication. -
What must be true about the
SELECTqueries combined withUNION?Answer
They must return the same number of columns, in a compatible order and compatible data types. -
Which queryβs column names appear in a
UNIONβs combined result set?Answer
The first query's column names (or aliases) β later queries' column names are ignored for output labeling purposes.