MySQL UNION Operator
MySQL UNION Operator
The UNION operator in MySQL is used to combine the result sets of two or more SELECT statements into a single result set.
⚠️ By default, UNION removes duplicate rows. If you want to include duplicates, use UNION ALL.
🔹 Syntax
Rules:
-
Each SELECT must have the same number of columns.
-
Corresponding columns must have similar data types.
-
Column names in the first SELECT are used as the result set column names.
🧠 Example Tables
Students2024
| id | name |
|---|---|
| 1 | John |
| 2 | Emma |
| 3 | Raj |
Students2025
| id | name |
|---|---|
| 4 | Sara |
| 5 | Aman |
| 2 | Emma |
🔹 SQL Query: Combine Students of 2024 and 2025
🔹 Result
| name |
|---|
| John |
| Emma |
| Raj |
| Sara |
| Aman |
✅ Notice:
Emmaappears in both tables but is shown only once because UNION removes duplicates.
🔹 Using UNION ALL (Include Duplicates)
| name |
|---|
| John |
| Emma |
| Raj |
| Sara |
| Aman |
| Emma |
✅ Duplicates are included.
🔹 Key Points
-
UNION combines results vertically (adds rows).
-
UNION removes duplicates by default.
-
UNION ALL keeps all duplicates.
-
Number and data types of columns must match in all SELECTs.
-
Useful for combining data from multiple tables or queries.
