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

SELECT column1, column2, ...
FROM table1
WHERE condition1
UNION

SELECT column1, column2, …
FROM table2
WHERE condition2;

Rules:

  1. Each SELECT must have the same number of columns.

  2. Corresponding columns must have similar data types.

  3. 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:

  • Emma appears 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

  1. UNION combines results vertically (adds rows).

  2. UNION removes duplicates by default.

  3. UNION ALL keeps all duplicates.

  4. Number and data types of columns must match in all SELECTs.

  5. Useful for combining data from multiple tables or queries.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *