MySQL UNION ALL Operator

MySQL UNION ALL Operator

The UNION ALL operator in MySQL is used to combine the result sets of two or more SELECT statements into a single result set, including duplicates.

⚠️ Unlike UNION, it does not remove duplicate rows.


🔹 Syntax


 

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 Using UNION ALL



 


🔹 Result

name
John
Emma
Raj
Sara
Aman
Emma

✅ Notice:

  • Emma appears twice because UNION ALL includes duplicates.

  • All rows from both tables are combined.


🔹 Difference Between UNION and UNION ALL

Feature UNION UNION ALL
Duplicates Removed Included
Performance Slightly slower Faster
Use Case Unique values Keep all rows

🔹 Key Points

  1. Combines two or more SELECT queries vertically.

  2. Preserves all duplicates.

  3. Faster than UNION because no duplicate removal is performed.

  4. Column count and data types must match across SELECT statements.

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 *