VillageSQL is a drop-in replacement for MySQL with extensions.
All examples on this page work on VillageSQL. Install Now →
UNION stacks results
on top of each other and lengthens it. Reach for it when 2 queries produce the
same shape of row and you want them in 1 list.
Open the client with mysql -u root -p sakila before you start.
How UNION works
COLUMN_LIST with the columns you want, and FIRST_TABLE and
SECOND_TABLE with the tables to read.
The 2 queries must return the same number of columns, and the server matches
those columns by position rather than by name.
UNION removes duplicate rows. UNION ALL keeps them, and is faster because
it does not have to compare anything.
Examples
1) UNION removes duplicates
Both halves here are the same query, so every row of the second is a duplicate of a row in the first.UNION deduplicates the combined result in 1 pass, so
repeats inside a half go the same way as repeats across the halves. The answer
matches SELECT DISTINCT on the same column.
2) UNION ALL keeps them
UNION ALL whenever you know there are no
duplicates, or when duplicates are the point.
3) Stack rows from different tables
This is whatUNION is really for: 2 tables that hold the same kind of thing.
A literal column says which half each row came from.
UNION does not promise an order
Neither half is guaranteed to arrive whole, or first. The server returns the rows in whatever order its plan produced them, so aUNION ALL of 2 identical
queries can interleave. ORDER BY at the end is the only way to fix it, the
same as with LIMIT and GROUP BY.
The halves must have the same number of columns
ORDER BY applies to the whole result
AnORDER BY at the end sorts the combined rows, not the last query. Name the
alias from the first half, which is what the result column is called.
ORDER BY and LIMIT inside them.
Summary
- Use
UNIONto stack the rows of 2 queries into 1 result. - Expect
UNIONto remove duplicates andUNION ALLto keep them. - Prefer
UNION ALLwhen you know there are none, because it does less work. - Give both halves the same number of columns, or get
ERROR 1222. - Expect the headings to come from the first query, and a trailing
ORDER BYto sort everything.
See also
- SELECT DISTINCT — removing duplicates from 1 query
- How joins work — combining tables side by side instead
- Subqueries — a query used as a value rather than stacked

