Intermediate · Lesson 14 of 20

UNION and UNION ALL

UNION combines result sets from two queries vertically (stacking rows).

SELECT first_name FROM employees WHERE department_id = 1
UNION
SELECT first_name FROM employees WHERE salary > 100000;

UNION removes duplicate rows automatically. UNION ALL keeps all rows, including duplicates.

Rules for UNION:

  • Both queries must have the same number of columns
  • Columns must have compatible data types
  • Column names come from the first query

Use UNION ALL when you know there are no duplicates - it's faster.

Check your understanding

What is the difference between UNION and UNION ALL?

Examples run on the employees sample database. Open any of them in the playground to experiment.