ADVERTISEMENT

SQL UNION / UNION ALL

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

ADVERTISEMENT