sql_union
SQL UNION and UNION ALL Operators: Combining Result Sets
Section titled “SQL UNION and UNION ALL Operators: Combining Result Sets”The SQL UNION and UNION ALL operators are used to combine the result sets of two or more SELECT statements into a single result set.
Understanding UNION and UNION ALL
Section titled “Understanding UNION and UNION ALL”The UNION operator combines result sets and removes duplicate rows. The UNION ALL operator also combines result sets but includes all rows, including duplicates.
Key Rules for Using UNION/UNION ALL:
- Same Number of Columns: Each
SELECTstatement within theUNIONorUNION ALLmust have the same number of columns in its select list. - Compatible Data Types: The data types of corresponding columns in each
SELECTstatement must be compatible (e.g., you can union aVARCHARwith anotherVARCHAR, or anINTwith anotherINT). The database will try to implicitly convert types if possible, but it’s best practice to ensure they match or are directly compatible. - Same Order of Columns: The columns in each
SELECTstatement must be in the same order.
SQL UNION Syntax
Section titled “SQL UNION Syntax”SELECT column_name(s) FROM table1UNIONSELECT column_name(s) FROM table2ORDER BY column_name; -- Optional: Applies to the final combined result setUNION by default selects only distinct values.
SQL UNION ALL Syntax
Section titled “SQL UNION ALL Syntax”SELECT column_name(s) FROM table1UNION ALLSELECT column_name(s) FROM table2ORDER BY column_name; -- Optional: Applies to the final combined result setUNION ALL selects all values, including duplicates. It is generally faster than UNION because it doesn’t perform the extra step of removing duplicates.
Column Names: The column names in the final result set are usually taken from the first SELECT statement.
Demonstration Database: Northwind
Section titled “Demonstration Database: Northwind”We’ll use data from the “Customers” and “Suppliers” tables in the Northwind database.
Selection from “Customers”:
CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
1Alfreds FutterkisteMaria AndersObere Str. 57Berlin12209Germany
2Ana Trujillo Emparedados y heladosAna TrujilloAvda. de la Constitución 2222México D.F.05021Mexico
3Antonio Moreno TaqueríaAntonio MorenoMataderos 2312México D.F.05023MexicoSelection from “Suppliers”:
SupplierIDSupplierNameContactNameAddressCityPostalCodeCountry
1Exotic LiquidsCharlotte Cooper49 Gilbert St.LondonEC1 4SDUK
2New Orleans Cajun DelightsShelley BurkeP.O. Box 78934New Orleans70117USA
3Grandma Kelly's HomesteadRegina Murphy707 Oxford Rd.Ann Arbor48104USASQL UNION Example: Unique Cities
Section titled “SQL UNION Example: Unique Cities”The following SQL statement selects all unique cities from both the “Customers” and “Suppliers” tables, ordered alphabetically.
SELECT City FROM CustomersUNIONSELECT City FROM SuppliersORDER BY City;If a city appears in both tables (e.g., London), it will only be listed once in the result.
SQL UNION ALL Example: All Cities (Including Duplicates)
Section titled “SQL UNION ALL Example: All Cities (Including Duplicates)”The following SQL statement uses UNION ALL to select all cities from both tables. If a city exists in both, or multiple times in one table (if we weren’t selecting distinct cities from each first), it would appear multiple times in the result.
SELECT City FROM CustomersUNION ALLSELECT City FROM SuppliersORDER BY City;SQL UNION ALL With WHERE Example: Combining Filtered Data
Section titled “SQL UNION ALL With WHERE Example: Combining Filtered Data”This example selects all German cities from “Customers” and all USA cities from “Suppliers”, combining them into one list. It also selects the country to differentiate.
SELECT City, Country, 'Customer' AS EntityType FROM CustomersWHERE Country = 'Germany'UNION ALLSELECT City, Country, 'Supplier' AS EntityType FROM SuppliersWHERE Country = 'USA'ORDER BY Country, City;Practical Application: UNION and UNION ALL are useful for combining data from similar tables (e.g., ActiveEmployees and ArchivedEmployees), or for creating consolidated reports from different data sources that share a common structure.