SkillByAIOpen interactive version →

Lesson 19 / 30

UNION

Stack results from several SELECT statements with UNION and UNION ALL and choose between deduplication and speed.

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
  • They require the same table name
  • UNION removes duplicate rows, UNION ALL keeps them
  • UNION is only for numbers
Answer

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