Stacking results with UNION
UNION stacks the results of two queries on top of each other, like pasting one list under
another:
SELECT email FROM employees WHERE leave_date IS NULL
UNION
SELECT contact_email FROM suppliers WHERE contact_email IS NOT NULLThe rules:
- Both queries must return the same number of columns, in the same order, with compatible types. Column names come from the first query.
UNIONremoves duplicate rows from the combined result.UNION ALLkeeps every row, and is faster, so use it whenever you know there are no duplicates or you want to keep them.
A label column shows where each row came from:
SELECT 'Customer' AS type, name FROM customers WHERE customer_type = 'Business'
UNION ALL
SELECT 'Supplier', name FROM suppliersUNION ALL is also handy for a small summary table built from several separate counts.