The UNION operator is used to merge the results from any combination of two or more queries or SELECT statements into a single table.
All queries in a UNION must request the same number of fields, though they don't have to be of the same size or data type. By default, a UNION only returns unique records, but by using the ALL predicate you ensure that all records are returned. This also makes the query run faster.
SELECT Name, City FROM Suppliers
WHERE Country = 'Mexico'
UNION SELECT Name, City FROM Customers
WHERE Country = 'Mexico';
Name City
Dell Mexico City
Computer Wholesale Warehouse Guadalajara
Computer Hardware Ltd. Cancun
Jorge Lopez Nogales
Rafael Sanchez Manzanillo
Jose Cruz Mexico City
Luis Castillo Cancun
(7 row(s) affected)
This example takes certain selected fields from the 'Customers' table and joins them onto the end of the same number of selected fields from the 'Suppliers' table.
SELECT Name, City, 'Supplier' AS Source
FROM Suppliers
WHERE Country = 'Canada'
UNION SELECT Name, City, 'Customer'
FROM Customers
WHERE Country = 'Canada'
ORDER BY City, Source;
Name City Source
Software and Peripherals Inc. Montreal Supplier
Colin Graphton Toronto Customer
Personal Computer Electronics Toronto Supplier
Jacque Jones Winnipeg Customer
Louie Franks Winnipeg Customer
(5 row(s) affected)
This example shows how by adding an ORDER BY clause at the end of the last query we can specify the order of the returned data.