UNION
A JOIN puts tables side by side, making the result wider. A UNION stacks the result of one query on top of another, making it longer.
SELECT ... FROM a UNION ALL SELECT ... FROM b
- Both SELECTs must return the same number of columns, in the same order, holding the same kind of value.
- The column names come from the first SELECT.
UNION ALLkeeps every row from both queries.UNIONon its own also removes duplicate rows, so each distinct row appears once.- An
ORDER BYgoes once, at the very end, and sorts the whole stacked result.
Use UNION ALL unless you really want duplicates removed. When a stacked query returns fewer rows than you expected, check whether it says UNION or UNION ALL.
UNION and UNION ALL side by side
The two tables in these examples
Two tiny made-up class lists. Notice that Cai is in both.
science_class| name |
|---|
| Ana |
| Ben |
| Cai |
arts_class| name |
|---|
| Cai |
| Dee |
Both examples run the same query and change only the word between the two SELECTs:
SELECT name FROM science_class UNION ALL SELECT name FROM arts_class
UNION ALL
Stacks the second result under the first and keeps every row. Cai appears twice, once from each class.
science_class UNION ALL arts_class gives 5 rows| name |
|---|
| Ana |
| Ben |
| Cai |
| Cai |
| Dee |
Use it when each row is a separate thing you want to keep or count, such as enrolments or payments.
UNION
Stacks the two results, then removes duplicate rows. Cai appears once.
science_class UNION arts_class gives 4 rows| name |
|---|
| Ana |
| Ben |
| Cai |
| Dee |
Use it when you want each distinct thing once, such as a list of people to contact. A row counts as a duplicate only when every column matches.
UNION or JOIN?
- To add columns from another table to each row:
JOIN - To add rows from another query underneath:
UNION ALLorUNION
One list that mixes two kinds of thing: the students who live in Tasmania, and the faculties.
SELECT first_name AS name, 'student' AS kind FROM students WHERE state = 'TAS' UNION ALL SELECT faculty_name, 'faculty' FROM faculties
This takes a few seconds the first time. Nothing leaves your computer.