UNION and UNION ALL
UNION
and UNION ALL
are SQL set operations that combine the results of two or more SELECT
queries.
UNION
removes duplicates, while UNION ALL
includes all rows, even duplicates.
They let you merge rows from different sources into one unified result.
Syntax
The basic syntax for UNION
and UNION ALL
is as follows:
SELECT column1, column2 FROM table1 UNION [ALL] SELECT column1, column2 FROM table2;
Rules:
- Each query must return the same number of columns
- The data types must be compatible
- The result set takes its column names from the first
SELECT
Example: CodeFriends Users in Two Years
Suppose we're analyzing registered users in 2023 and 2024.
We have two tables:
users_2023
user_id | name |
---|---|
1 | Sofia |
2 | Ethan |
3 | Aisha |
users_2024
user_id | name |
---|---|
1 | Sofia |
3 | Aisha |
4 | Noah |
Example: UNION
The following query returns all users from both years.
SELECT user_id, name FROM users_2023 UNION SELECT user_id, name FROM users_2024;
Result:
user_id | name |
---|---|
1 | Sofia |
2 | Ethan |
3 | Aisha |
4 | Noah |
UNION
removes duplicates, so only one entry per unique row is returned.
Example: UNION ALL
The following query returns all users from both years, including duplicates.
SELECT user_id, name FROM users_2023 UNION ALL SELECT user_id, name FROM users_2024;
Result:
user_id | name |
---|---|
1 | Sofia |
2 | Ethan |
3 | Aisha |
1 | Sofia |
3 | Aisha |
4 | Noah |
When to Use
- Use
UNION
when you want to eliminate duplicates - Use
UNION ALL
when performance matters or duplicate rows are meaningful
UNION ALL
is typically faster because it skips the deduplication step.
UNION and UNION ALL return the same result when there are no duplicate rows in the combined datasets.
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Tables
Execution Result