SQL ยท Chapter 20 of 42

SQL UNION

UNION combines the results of two SELECTs into one, stacking them vertically. Columns must match in count and compatible types.

`UNION` removes duplicates. `UNION ALL` keeps them (and is faster).

UNION vs UNION ALL

UNION does a dedupe pass โ€” slower. UNION ALL is faster and preferred when you know rows are distinct.

Example 1 (sql)
SELECT name FROM staff
UNION
SELECT name FROM interns;
Output
distinct names from both tables

UNION deduplicates.

Example 2 (sql)
SELECT id, 'staff' AS kind FROM staff
UNION ALL
SELECT id, 'intern' FROM interns;
Output
every row, tagged with source

UNION ALL keeps duplicates and preserves counts.

Key points

  • Combines two queries vertically.
  • Column count and types must match.
  • UNION removes duplicates.
  • UNION ALL is faster and keeps duplicates.
๐Ÿ’ก Note: ORDER BY only appears at the END, after the final SELECT โ€” it applies to the combined result.

๐Ÿ“ Quick Quiz

1. UNION requires the two selects to have:

2. Which is faster?

3. UNION removes: