TExcelTAD
Home › PostgreSQL › PostgreSQL UNION, INTERSECT & EXCEPT

PostgreSQL UNION, INTERSECT & EXCEPT

Joins put tables side by side (more columns). Set operations stack query results on top of each other (more rows). PostgreSQL supports the three classic set operations:

Operator Result
UNION rows that appear in either query, duplicates removed
UNION ALL all rows from both queries, duplicates kept
INTERSECT rows that appear in both queries
EXCEPT rows of the first query that are not in the second

The queries must return the same number of columns with compatible types. Column names come from the first query.

UNION

One list of people from two tables: the UK customers and the booksellers on the staff, sorted by name.

pgsql · try it yourself
SELECT first_name || ' ' || last_name AS name, 'customer' AS kind
FROM customers
WHERE country = 'UK'
UNION
SELECT name, 'employee'
FROM employees
WHERE job_title = 'Bookseller'
ORDER BY name;
     name      |   kind
---------------+----------
 Ben Carter    | customer
 Isla Murray   | customer
 Lucy Evans    | employee
 Olivia Martin | customer
 Paul Becker   | employee
(5 rows)

The ORDER BY at the end sorts the combined result.

UNION vs UNION ALL

UNION removes duplicate rows, which costs a sort or a hash step. UNION ALL just appends:

pgsql · try it yourself
SELECT country FROM authors WHERE country IN ('UK', 'Japan', 'Italy')
UNION
SELECT country FROM customers WHERE country IN ('UK', 'Japan', 'Italy')
ORDER BY country;

SELECT country FROM authors WHERE country IN ('UK', 'Japan', 'Italy')
UNION ALL
SELECT country FROM customers WHERE country IN ('UK', 'Japan', 'Italy')
ORDER BY country;
 country
---------
 Italy
 Japan
 UK
(3 rows)

 country
---------
 Italy
 Italy
 Japan
 Japan
 UK
 UK
 UK
 UK
(8 rows)

Tip: When you know the parts can't overlap, or duplicates are fine, use UNION ALL. It is faster and doesn't hide data by accident.

INTERSECT

Countries that have both an author and a customer:

pgsql · try it yourself
SELECT country FROM authors
INTERSECT
SELECT country FROM customers
ORDER BY country;
 country
---------
 Canada
 Germany
 Italy
 Japan
 UK
(5 rows)

EXCEPT

Books that are in stock but have never been ordered. EXCEPT returns the ids of the first query that are missing from the second:

pgsql · try it yourself
SELECT id FROM books WHERE stock > 0
EXCEPT
SELECT book_id FROM order_items
ORDER BY id;
 id
----
 16
(1 row)

Order matters: A EXCEPT B is not the same as B EXCEPT A.

Column count and types must line up

pgsql · try it yourself
SELECT title, price FROM books
UNION
SELECT name FROM authors;

SELECT title FROM books
UNION
SELECT birth_year FROM authors;
ERROR:  each UNION query must have the same number of columns
LINE 3: SELECT name FROM authors;
               ^
ERROR:  UNION types text and integer cannot be matched
LINE 3: SELECT birth_year FROM authors;
               ^

Cast when the types differ: SELECT birth_year::text FROM authors.

A practical example: a timeline

Set operations are great for merging events from different tables into one list. A small activity log for customer 1:

pgsql · try it yourself
SELECT joined AS day, 'joined the shop' AS event
FROM customers WHERE id = 1
UNION ALL
SELECT order_date, 'placed order ' || id
FROM orders WHERE customer_id = 1
ORDER BY day;
    day     |      event
------------+-----------------
 2023-01-15 | joined the shop
 2024-01-05 | placed order 1
 2024-02-02 | placed order 3
 2024-07-09 | placed order 12
(4 rows)

Test yourself

What does UNION do with duplicate rows?

  1. Keeps them
  2. Removes them
  3. Raises an error
  4. Counts them

Which operator returns rows present in the first query but not in the second?

  1. INTERSECT
  2. UNION
  3. EXCEPT
  4. MINUS JOIN

Where do the column names of a UNION result come from?

  1. The last query
  2. The first query
  3. They are numbered
  4. Both, joined with an underscore