Video in progress

How do UNION and UNION ALL differ in result and in speed?

UNION combines the results of two queries and removes duplicate rows, while UNION ALL appends everything as is. UNION ALL is faster because it doesn't need to sort or hash to look for duplicates.

📖 Answer

SELECT email FROM customers
UNION
SELECT email FROM newsletter_subscribers;   -- each email once

SELECT email FROM customers
UNION ALL
SELECT email FROM newsletter_subscribers;   -- an email in both appears twice

Many developers write UNION out of habit, but if the results can't overlap anyway (say, the tables orders_2025 and orders_2026), that is wasted work. On a million rows UNION needs extra memory and time; in EXPLAIN you'll see a HashAggregate or Unique + Sort node.

In both cases the rules are the same: the number of columns must match and the types must be compatible. Column names come from the first query. A single ORDER BY goes at the very end and applies to the whole result.