π 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 UNIONandUNION 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
| Operator | Duplicates | Performance | Use Case | 
|---|---|---|---|
| UNION | Removed | Slightly slower | Combine without duplicates | 
| UNION ALL | Preserved | Faster | Include all rows (even duplicates) | 
π 4. UNION Requirements
- All SELECTqueries 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 UNIONwhen deduplication is needed | Expecting column mismatch to work | 
| Use UNION ALLfor faster performance | Sorting inside individual queries | 
| Match data types and positions exactly | Forgetting 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 UNIONto remove duplicates
- Use UNION ALLto keep them
- Ensure matching columns and data types
- Final ORDER BYsorts 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 :
