MySQL Union

UNION combines the result sets of two or more SELECT statements into one result set, removing duplicate rows by default unless you use UNION ALL.

Combining Result Sets with UNION

UNION stacks the rows returned by two or more SELECT statements on top of each other to produce a single combined result. Unlike a JOIN, which combines columns side by side, UNION combines rows — so each SELECT in the union must return the same number of columns, and the columns in matching positions must have compatible data types.

UNION vs UNION ALL

Plain UNION automatically removes duplicate rows from the combined result, which means MySQL has to sort or hash the entire result set to find and discard repeats. UNION ALL skips that deduplication step entirely and simply concatenates the result sets, which makes it noticeably faster on large data. Use UNION ALL whenever you know the sources won't overlap or you don't care about duplicates.

  • Every SELECT in the UNION must return the same number of columns
  • Columns in the same position must have compatible data types
  • The output column names are taken from the first SELECT statement
  • Only one ORDER BY is allowed, and it must appear after the final SELECT, applying to the whole combined result

Combine Two Customer Lists

SELECT name, email FROM active_customers
UNION
SELECT name, email FROM archived_customers;

Because ORDER BY sorts the final combined output rather than each individual SELECT, you write it only once, at the very end of the statement, and it can reference the column names or aliases established by the first SELECT.

Keep Every Row, Including Duplicates

SELECT name, email FROM active_customers
UNION ALL
SELECT name, email FROM archived_customers
ORDER BY name;
QueryRows ReturnedDuplicates Removed
UNION148Yes
UNION ALL152No

Tag Rows With Their Source Table

SELECT name, 'employee' AS person_type FROM employees
UNION ALL
SELECT name, 'contractor' AS person_type FROM contractors
ORDER BY person_type, name;
Note: Reach for UNION ALL by default and only switch to UNION when you've confirmed duplicates are possible and unwanted — it saves MySQL an expensive sort and dedup pass.
Note: Mismatched column counts or incompatible types between the SELECTs raise an error immediately. Also remember that WHERE, GROUP BY, and LIMIT belong to their own individual SELECT, but ORDER BY belongs to the union as a whole and can only appear once, at the end.

Exercise: MySQL Union

What is the primary purpose of the UNION operator?