Lesson 19 / 28

UNION

Stack results from two SELECT queries.

Combining result sets

UNION stacks rows from two queries with the same column count, removing duplicates. UNION ALL keeps duplicates and is faster.

SELECT name FROM customers WHERE id = 1
UNION
SELECT name FROM customers WHERE id = 2;

Output:

name
Asha Rao
Rahul Mehta

Quick check: What's the key difference between UNION and UNION ALL?

  • UNION ALL sorts the results
  • UNION removes duplicate rows, UNION ALL keeps them
  • They require the same table name
Answer

UNION removes duplicate rows, UNION ALL keeps them — UNION dedupes (extra work); UNION ALL doesn't, so it's faster.