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 allow you to merge rows from different sources into a single 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 corresponding columns must have compatible data types
- 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: Using UNION to remove duplicates
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: Using UNION ALL to keep duplicates
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 should I use UNION vs UNION ALL?
- Use
UNIONwhen you want to eliminate duplicates - Use
UNION ALLwhen performance is important or duplicate rows carry meaning
UNION ALLis typically faster since it avoids 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