Class 39 of 58 • Relational Joins & Set Operations

SQL UNION & UNION ALL: Combining Query Result Sets

While SQL Joins combine columns horizontally across tables, the UNION and UNION ALL set operators combine query results vertically by stacking rows from two or more SELECT statements into a single unified result set.


The 3 Strict Rules of UNION

• Rule 1: Both queries must project the exact same number of columns.

• Rule 2: Columns in corresponding positions must share compatible data types.

• Rule 3: Column header names are inherited from the first SELECT statement.


UNION (Deduplicated) vs UNION ALL (Fast & All Rows)

-- 1. UNION: Combines customer and supplier cities, eliminating duplicates
SELECT city FROM customers
UNION
SELECT city FROM suppliers;

-- 2. UNION ALL: Preserves all occurrences without deduplication overhead (FAST!)
SELECT student_id, first_name, 'Undergraduate' AS academic_level FROM students
UNION ALL
SELECT student_id, first_name, 'Postgraduate' AS academic_level FROM alumni;
Performance Best Practice: Always default to UNION ALL unless you specifically need duplicate elimination. UNION forces the database to sort the entire merged dataset in temporary disk/memory storage to discard duplicates.

Congratulations! You have completed Module 6 (Joins & Set Operations). Now let us enter the advanced realm for senior software engineers starting with SQL Subqueries & Nested Queries!


Frequently Asked Questions (FAQ)

UNION combines result sets and performs an expensive sort operation to remove duplicate rows. UNION ALL combines result sets without removing duplicates, making UNION ALL significantly faster.

Each SELECT query in the UNION must have: (1) the exact same number of columns, (2) columns in matching positional order, and (3) compatible data types.

Place a single ORDER BY clause at the very end of the final SELECT query to sort the combined output.

Next Step in Your SQL Database Learning Path:

Proceed to the next class in sequence to build production mastery of relational database architecture.

Continue to Class 40: Subqueries & Nested Queries → Previous: ← CROSS & SELF JOIN | Full Syllabus


Related SQL Masterclass Lessons & Recommended Next Topics

Horizontal vs Vertical Sets →

Difference between joining tables and unioning query results.

Emulating Full Outer Join →

Using UNION to merge left and right outer join queries.

SELECT Queries →

Ensuring matching column counts and compatible data types.

Subqueries & Set Operations →

Embedding union queries inside derived tables.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Reddit

You may also like this!