πŸ”— SQL Joins & Combinations
Estimated reading: 2 minutes 42 views

πŸ”€ SQL UNION – Merge Query Results with UNION and UNION ALL

🧲 Introduction – What is SQL UNION?

The UNION operator in SQL lets you combine the results of two or more SELECT queries into a single result set. It removes duplicates by default, and it’s often used when queries return similar data from different tables or filters.

🎯 In this guide, you’ll learn:

  • Syntax and rules for UNION and UNION ALL
  • Differences between the two
  • Real-world use cases and tips

βœ… 1. Basic SQL UNION Syntax

SELECT column1, column2 FROM table1
UNION
SELECT column1, column2 FROM table2;

βœ… Combines two result sets, removes duplicate rows.


πŸ” 2. UNION ALL – Keep All Rows (Duplicates Included)

SELECT city FROM customers
UNION ALL
SELECT city FROM suppliers;

βœ… Returns all rows including duplicates.


πŸ“Š 3. UNION vs UNION ALL

OperatorDuplicatesPerformanceUse Case
UNIONRemovedSlightly slowerCombine without duplicates
UNION ALLPreservedFasterInclude all rows (even duplicates)

πŸ”Ž 4. UNION Requirements

  • All SELECT queries must have the same number of columns
  • Corresponding columns must be of compatible data types
  • Column names in the final result use the first query’s column names

🧩 5. Example – Multiple User Sources

SELECT name, email FROM customers
UNION
SELECT name, email FROM employees;

βœ… Creates a unified contact list.


πŸ”„ 6. ORDER BY with UNION

SELECT name FROM customers
UNION
SELECT name FROM suppliers
ORDER BY name;

βœ… ORDER BY applies to the entire result set, not individual queries.


πŸ“˜ Best Practices

βœ… Recommended❌ Avoid This
Use UNION when deduplication is neededExpecting column mismatch to work
Use UNION ALL for faster performanceSorting inside individual queries
Match data types and positions exactlyForgetting ORDER BY applies globally

πŸ“Œ Summary – Recap & Next Steps

The UNION operator merges query outputs for unified reporting or combined filters. It helps simplify multiple queries into one result.

πŸ” Key Takeaways:

  • Use UNION to remove duplicates
  • Use UNION ALL to keep them
  • Ensure matching columns and data types
  • Final ORDER BY sorts the full result set

βš™οΈ Real-World Relevance:
Used in data exports, combined analytics, log aggregation, and multi-source reports.

➑️ Next: Explore INTERSECT, EXCEPT, and conditional CASE expressions.


❓ FAQ – SQL UNION

❓ What is the difference between UNION and UNION ALL?

βœ… UNION removes duplicates; UNION ALL does not.

❓ Can I use ORDER BY in both queries?

❌ No. Use ORDER BY once at the end.

❓ Can UNION work with different column names?

βœ… Yes, but only the column names from the first query are used.

❓ Does UNION preserve row order?

❌ No. Use ORDER BY to control output order.


Share Now :

Leave a Reply

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

Share

πŸ”€ SQL UNION

Or Copy Link

CONTENTS
Scroll to Top