SQL Union

UNION combines the result sets of two or more SELECT statements and removes duplicate rows.

On this page

SQL UNION

The UNION operator is used to combine the result sets of two or more SELECT statements into a single result set.

UNION Rules

  • Each SELECT statement must have the same number of columns
  • The columns must be in the same order
  • The column data types must be compatible
  • UNION removes duplicate rows by default

Basic Syntax

SELECT column1, column2
FROM table1
UNION
SELECT column1, column2
FROM table2;

Example: Combine Customers and Suppliers

Suppose you want a single list of all contact names from customers and suppliers:

SELECT name AS contact_name, city
FROM customers
UNION
SELECT name AS contact_name, city
FROM suppliers;

Because UNION removes duplicates, identical rows will appear only once.

Using ORDER BY with UNION

When using UNION, ORDER BY must be applied to the final combined result set (at the end).

SELECT name AS contact_name, city
FROM customers
UNION
SELECT name AS contact_name, city
FROM suppliers
ORDER BY contact_name;

UNION vs JOIN

  • UNION stacks results vertically (adds rows)
  • JOIN combines tables horizontally (adds columns)

Common Mistakes

  • Using different column counts in the SELECT statements
  • Trying to ORDER BY inside the first SELECT (ORDER BY belongs at the end)
  • Expecting UNION to keep duplicates (use UNION ALL for that)

Next Step

Continue with SQL UNION ALL to learn how to combine results without removing duplicates.