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.

Practice it on a real question

All SELECT & filtering questions

Practice on your iPhone

Query Dojo for iPhone has 85 interview questions, timed mock interviews and a tile builder, so you can write queries without a keyboard.

Get the app