Lecture

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:

UNION syntax
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_idname
1Sofia
2Ethan
3Aisha

users_2024

user_idname
1Sofia
3Aisha
4Noah

Example: UNION

The following query returns all users from both years.

Using UNION
SELECT user_id, name FROM users_2023 UNION SELECT user_id, name FROM users_2024;

Result:

user_idname
1Sofia
2Ethan
3Aisha
4Noah

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.

Using UNION ALL
SELECT user_id, name FROM users_2023 UNION ALL SELECT user_id, name FROM users_2024;

Result:

user_idname
1Sofia
2Ethan
3Aisha
1Sofia
3Aisha
4Noah

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.

Quiz
0 / 1

UNION and UNION ALL return the same result when there are no duplicate rows in the combined datasets.

True
False

Lecture

AI Tutor

Design

Upload

Notes

Favorites

Help

Code Editor

Run
Generate

Tables

Execution Result