All SQL topics
SQL TOPIC

SQL UNION and UNION ALL: combine compatible result sets

UNION stacks rows and removes duplicates; UNION ALL keeps every row from both queries.

Both SELECT branches must return the same number of columns in the same order. Put ORDER BY after the final branch if the combined list needs sorting.

Use UNION when duplicate rows are unwanted. Use UNION ALL when they are meaningful or when each branch already represents a distinct category.

Worked example

Make one outreach list of business customers and German customers.

SELECT name, email FROM customers WHERE segment = 'business'
UNION
SELECT name, email FROM customers WHERE country = 'Germany'
ORDER BY name;
Result on the sample data
nameemail
Anna SchmidtANNA.SCHMIDT@example.de
Anna Schmidtanna.schmidt@example.de
Ciara Walshciara.walsh@example.ie
Elena Garcíaelena.garcia@example.es
Emma de Vriesemma.devries@example.nl
Giorgos Ioannougiorgos.ioannou@example.com
Jonas Beckerjonas.becker@example.com
Marco Bianchimarco.bianchi@example.it
Mia Webermia.weber@example.de
Sean Byrnesean.byrne@example.ie

Common mistakes

  • Using UNION ALL for overlapping lists and contacting a person twice.
  • Trying to combine branches with different column counts.