UNION stacks the results of two or more queries into one result. Where a join puts tables side by side, a union puts results one above the other.
SELECT column1, column2 FROM table1UNIONSELECT column1, column2 FROM table2;For the rows to stack, the queries must line up:
- Each query returns the same number of columns.
- Columns in the same position hold the same kind of data.
- The result takes its column names from the first query.
The examples use the Invoices, Suppliers and Crew tables from the example database.
Every supplier the company knows of, whether from an invoice or from the approved list:
SELECT Supplier FROM InvoicesUNIONSELECT Name FROM SuppliersORDER BY Supplier;| Supplier |
|---|
| Ashby Camera Hire |
| Hartwell Lighting |
| Kestrel Catering |
| Northgate Transport |
UNION removes duplicate rows. Kestrel Catering appears on two invoices and on the approved list, but is listed once.
UNION ALL
Section titled “UNION ALL”UNION ALL keeps every row, duplicates included:
SELECT Supplier FROM InvoicesUNION ALLSELECT Name FROM SuppliersORDER BY Supplier;| Supplier |
|---|
| Ashby Camera Hire |
| Hartwell Lighting |
| Hartwell Lighting |
| Kestrel Catering |
| Kestrel Catering |
| Kestrel Catering |
| Northgate Transport |
Seven rows: four invoices and three approved suppliers. UNION ALL is also faster, since the database does not have to look for duplicates, so prefer it whenever duplicates cannot occur or do not matter.
Labelling where each row came from
Section titled “Labelling where each row came from”A constant value in each query labels its rows. A list of everyone in accounts alongside the approved suppliers:
SELECT 'Crew' AS Type, Name FROM Crew WHERE Department = 'Accounts'UNION ALLSELECT 'Supplier', Name FROM SuppliersORDER BY Type, Name;| Type | Name |
|---|---|
| Crew | Lucy Brennan |
| Crew | Priya Nair |
| Crew | Tom Hale |
| Supplier | Hartwell Lighting |
| Supplier | Kestrel Catering |
| Supplier | Northgate Transport |
The alias Type is given in the first query only, and names the column for the whole result. Each query can have its own WHERE clause, but a single ORDER BY at the very end sorts the combined result.