0PricingLogin
SQL Interview Prep · Lesson

UNION vs UNION ALL

The deduplication and performance difference, and why UNION ALL is usually intended.

Why Interviewers Ask About UNION

Set operations stack one result set on top of another, vertically. UNION and UNION ALL are the first set operators interviewers reach for because the difference between them is a one-line answer that reveals whether you understand cost.

The question is almost always phrased as: "What is the difference between UNION and UNION ALL, and which should you use?" A strong answer mentions deduplication, ordering, and performance in one breath.

What UNION Does

UNION combines the rows of two queries into a single result set and then removes duplicate rows. Two rows are duplicates only if every column matches.

To remove duplicates the engine must sort or hash all combined rows, which is real work. UNION returns a set in the mathematical sense: no repeats.

SELECT city FROM customers
UNION
SELECT city FROM suppliers;

All lessons in this course

  1. UNION vs UNION ALL
  2. Column Count and Type Compatibility
  3. INTERSECT and EXCEPT for Comparison
  4. Emulating Set Operations With Joins
← Back to SQL Interview Prep