# Topic 36: UNION & UNION ALL
Combining result sets vertically, deduplication overhead, column type compatibility, and set theory.
1. Definition
UNION combines the result sets of two or more SELECT queries vertically into a single dataset, automatically deduplicating rows. UNION ALL combines results without deduplication.
2. Explain Like I'm 5
UNION ALL is taping two lists together end-to-end. UNION is taping them together, reading every line, and crossing out any duplicates.
3. Animation & Visual Simulation
Interactive Engine TraceUNION & UNION ALL Visual Simulator
SELECT id, title, 'article' AS type FROM articles
UNION ALL
SELECT id, title, 'video' AS type FROM videos
ORDER BY title;Active InputStep 1: Input & Parsing Stage
Initiating UNION & UNION ALL
Checking Table Invariants
The database engine inspects active tables, verifies permissions, and prepares the physical operation.
4. Real-World Example
Combining active customers and archived customers into a master mailing list.
| Operation | List A (100 rows) | List B (50 rows) | Output Rows |
|---|---|---|---|
| UNION ALL | 100 rows | 50 rows | 150 rows (Instant) |
| UNION | 100 rows | 50 rows | 130 rows (Deduplicated, slower) |
5. SQL Syntax
ANSI SQL / PostgreSQL DialectSELECT id, email, 'customer' AS user_type FROM customers UNION ALL SELECT id, email, 'contractor' AS user_type FROM contractors ORDER BY email;
SELECT city FROM domestic_suppliers UNION SELECT city FROM international_suppliers;
6. Important Rules & Behaviors
| Rule | Behavioral Explanation |
|---|---|
| Column Count & Type Compatibility | All SELECT statements in the UNION must have the exact same number of columns with compatible data types. |
| Column Names from First Query | The final result set inherits column names and aliases from the first SELECT query. |
| Single ORDER BY at End | Only one ORDER BY clause is permitted, placed at the very end of the entire union pipeline. |
| UNION deduplication sort overhead | UNION executes a mandatory sorting or hash deduplication pass; UNION ALL streams rows with zero deduplication cost. |
| Column count and type matching | Both queries must project the exact same number of columns with compatible data types. |
7. Deep Dive: Performance: Why UNION ALL should be your Default
UNION performs an expensive Unique Sort or HashAggregate over the entire combined dataset to eliminate duplicates. If you know the two sets are disjoint (e.g. current orders and archived orders), or if duplicates are acceptable, UNION ALL saves immense CPU and memory.
-- SLOW (Sorts and deduplicates 2 million rows in RAM): SELECT id FROM current_logs UNION SELECT id FROM archived_logs; -- FAST (Streams rows immediately without memory sorting): SELECT id FROM current_logs UNION ALL SELECT id FROM archived_logs;
8. Advantages & Disadvantages
Advantages
- •Combines disparate tables with identical schemas into unified feeds.
- •UNION ALL provides high-throughput zero-cost set concatenation.
Disadvantages & Trade-offs
- •UNION triggers expensive in-memory sort or hash deduplication.
9. Common Interview Questions
Q1.What is the exact physical execution difference between UNION and UNION ALL?
UNION ALL simply concatenates the tuple streams from both queries and streams them directly to the client socket with zero sorting and zero buffering (O(N + M)). UNION concatenates the streams and then forces a mandatory deduplication phase: the engine must either sort all rows or build an in-memory hash set to eliminate duplicates, consuming significant CPU, memory, and potential disk sort spills.
Q2.Why should software engineers default to UNION ALL unless duplicate removal is strictly required?
Because UNION incurs a severe O(N log N) sort or hash overhead. If the two queries are known to produce disjoint sets (e.g. querying active_users and archived_users where IDs never overlap), using UNION wastes massive CPU and memory resources deduplicating records that could never be duplicates. Always default to UNION ALL.
Q3.How are column names determined in a UNION query?
Column names in the final result set are determined entirely by the projection list of the FIRST query in the UNION chain. Any column aliases specified in subsequent queries are completely ignored by the engine.
Q4.Can you use ORDER BY on individual queries within a UNION chain?
In standard SQL, you cannot place ORDER BY on individual branches of a UNION without wrapping them in parentheses or subqueries. An ORDER BY placed at the end of a UNION chain sorts the FINAL concatenated result set after all unions and deduplications have completed.
Q5.What are the rules for data type compatibility in UNION queries?
Columns in matching positions must have compatible data types. If Query 1 has an INTEGER and Query 2 has a NUMERIC, the engine implicitly promotes the column to NUMERIC. However, if Query 1 has an INTEGER and Query 2 has a VARCHAR, standard engines will throw a type mismatch error unless explicitly cast.
10. Interview-Ready Answer
“UNION vertically combines query results with automatic deduplication, while UNION ALL retains all rows without deduplication. Unless duplicate elimination is an explicit business requirement, UNION ALL should always be preferred for performance.”
11. Quick Test
Query 1 returns 50 rows; Query 2 returns 30 rows. Exactly 10 rows exist in both results. How many rows will UNION return?