Tools

SQL UNION / UNION ALL

Share:
Article Summary

UNION and UNION ALL combine results from two or more SELECT queries.Both must have the same number of columns with compatible data types. πŸ”Ή Syntax πŸ”Ή Example: Merge Customers from Two Regions πŸ”Ή Key Differences Feature UNION UNION ALL Duplicates Removed Included Performance Slower (due to deduplication) Faster Use When You want distinct results You […]

UNION and UNION ALL combine results from two or more SELECT queries.
Both must have the same number of columns with compatible data types.

πŸ”Ή Syntax

-- Removes duplicates
SELECT column1, column2 FROM table1
UNION
SELECT column1, column2 FROM table2;

-- Keeps duplicates
SELECT column1, column2 FROM table1
UNION ALL
SELECT column1, column2 FROM table2;

πŸ”Ή Example: Merge Customers from Two Regions

-- Unique customers only
SELECT customer_name FROM customers_us
UNION
SELECT customer_name FROM customers_uk;

-- Include duplicates
SELECT customer_name FROM customers_us
UNION ALL
SELECT customer_name FROM customers_uk;

πŸ”Ή Key Differences

FeatureUNIONUNION ALL
DuplicatesRemovedIncluded
PerformanceSlower (due to deduplication)Faster
Use WhenYou want distinct resultsYou need all results

🧠 Quick Recap

Key PointExplanation
UNIONCombines results & removes duplicates
UNION ALLCombines results with duplicates
Column matchSame number and types of columns required
Use casesMerge similar datasets (e.g., logs, users)

🧩 Use UNION for clean merged data
🧩 Use UNION ALL for full raw results

Was this helpful?

Written by

W3buddy
W3buddy

Explore W3Buddy for in-depth guides, breaking tech news, and expert analysis on AI, cybersecurity, databases, web development, and emerging technologies.