UNION and UNION ALL

Stack the rows of two queries into one result. UNION removes repeats; UNION ALL keeps them.

Syntax

SELECT … UNION SELECT …;
SELECT … UNION ALL SELECT …;
  • Both queries must return the same number of columns, with compatible types.

Example

SELECT city FROM customers UNION SELECT category FROM products;

Every city and every product category, each listed once.

Tables used: customers, products. Try it in a lesson below.

Common mistakes

  • Column names come from the first query. Give them aliases there.
  • UNION is slower than UNION ALL because it must remove duplicates. Use UNION ALL when repeats are fine.

Practise it