Skip to content
Back to 50 Concepts
Topic 36 of 50query-executionIntermediate

# 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.

Relational Invariant:Deterministic relational algebra contract evaluated by the Cost-Based Optimizer.

2. Explain Like I'm 5

Intuitive mental model for beginners

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 Trace
Interactive Engine Simulation

UNION & UNION ALL Visual Simulator

Step 1 of 3
SQL>SELECT id, title, 'article' AS type FROM articles UNION ALL SELECT id, title, 'video' AS type FROM videos ORDER BY title;Active Input

Step 1: Input & Parsing Stage

Engine Action: Validate SQL syntax and resolve schema metadata for UNION & UNION ALL
SQL Input

Initiating UNION & UNION ALL

Schema Catalog

Checking Table Invariants

How the Database Executes This:

The database engine inspects active tables, verifies permissions, and prepares the physical operation.

💡 Card decks: UNION ALL shuffles two decks together as-is; UNION goes through the combined deck and throws away all duplicate cards.

4. Real-World Example

Combining active customers and archived customers into a master mailing list.

Result Comparison
OperationList A (100 rows)List B (50 rows)Output Rows
UNION ALL100 rows50 rows150 rows (Instant)
UNION100 rows50 rows130 rows (Deduplicated, slower)
Relational walkthrough: UNION ALL preserves all rows without memory-intensive sorting or hashing.

5. SQL Syntax

ANSI SQL / PostgreSQL Dialect
Step 1: High performance combination with UNION ALL
SELECT id, email, 'customer' AS user_type FROM customers
UNION ALL
SELECT id, email, 'contractor' AS user_type FROM contractors
ORDER BY email;
UNION ALL does not sort or deduplicate, making it much faster.
Step 2: Distinct set union with UNION
SELECT city FROM domestic_suppliers
UNION
SELECT city FROM international_suppliers;
Removes duplicate cities from the combined list.

6. Important Rules & Behaviors

RuleBehavioral Explanation
Column Count & Type CompatibilityAll SELECT statements in the UNION must have the exact same number of columns with compatible data types.
Column Names from First QueryThe final result set inherits column names and aliases from the first SELECT query.
Single ORDER BY at EndOnly one ORDER BY clause is permitted, placed at the very end of the entire union pipeline.
UNION deduplication sort overheadUNION executes a mandatory sorting or hash deduplication pass; UNION ALL streams rows with zero deduplication cost.
Column count and type matchingBoth 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;
Caution: Never use UNION when UNION ALL is sufficient; the deduplication sort can spill to disk.

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

Scenario Question:

Query 1 returns 50 rows; Query 2 returns 30 rows. Exactly 10 rows exist in both results. How many rows will UNION return?

Select your answer: