UNION, INTERSECT and EXCEPT

Topic 3 of 4 in Combining queries9 min readBeginnerFree course

Overview

Joins combine tables side by side, adding columns. Set operations combine query results one on top of another, working with whole rows. They answer questions like “everyone we know — customers and staff — in one list”, “cities that appear in both lists” and “products in the catalogue but not in any order”.

UNION, INTERSECT and EXCEPT, shown as two overlapping circles. UNION returns rows in either result, with duplicates removed. INTERSECT returns rows in both. EXCEPT returns rows in the first result but not the second. An example: SELECT city FROM customers INTERSECT SELECT city FROM customers WHERE id IN (SELECT customer_id FROM orders). Both queries must return the same number of columns, with compatible types. UNION ALL keeps duplicates and is faster. Column names come from the first query, and ORDER BY applies to the combined result.

UNION ALL: stacking results

Bean & Leaf wants one list of every person in the database. Customers and employees live in different tables with different columns, but each query can produce the same shape — a name and a role:

SQL
SELECT first_name || ' ' || last_name AS person, 'customer' AS role
FROM customers
WHERE country = 'India'
UNION ALL
SELECT name, 'employee'
FROM employees
WHERE manager_id = 1
ORDER BY person;
Text
   person   |   role   
------------+----------
 Asha Rao   | customer
 Farhan Ali | customer
 Isha Patel | customer
 Lina Costa | employee
 Tom Hughes | employee
(5 rows)

The rules:

  • Both queries must return the same number of columns, in the same order.
  • Matching columns must have compatible types — text with text, numbers with numbers.
  • Column names come from the first query; the aliases in the second are ignored, so there’s no need to write them.
  • One ORDER BY at the very end sorts the combined result. (LIMIT likewise applies to the whole thing.)

UNION: stacking without duplicates

UNION without ALL also removes duplicate rows from the combined result — like adding DISTINCT. Here are the countries of customers in three cities, plus the countries of customers whose orders are currently on their way:

SQL
SELECT country FROM customers WHERE city IN ('Pune', 'Mumbai', 'Leeds')
UNION
SELECT c.country
FROM orders AS o
JOIN customers AS c ON c.id = o.customer_id
WHERE o.status = 'shipped'
ORDER BY country;
Text
 country 
---------
 France
 India
 UK
 USA
(4 rows)

The first query produced India three times and the UK once; the second, the USA and France. UNION kept one of each. With UNION ALL you’d see India three times:

SQL
SELECT country FROM customers WHERE city IN ('Pune', 'Mumbai', 'Leeds')
UNION ALL
SELECT c.country
FROM orders AS o
JOIN customers AS c ON c.id = o.customer_id
WHERE o.status = 'shipped'
ORDER BY country;
Text
 country 
---------
 France
 India
 India
 India
 UK
 USA
(6 rows)

Which to use? If the two results can’t overlap — like customers and employees tagged with different roles — or you want the duplicates, use UNION ALL. Removing duplicates means sorting or hashing the whole result, which costs time on big data, and it can hide rows you meant to keep. Reach for plain UNION only when you specifically want distinct rows.

INTERSECT: in both

INTERSECT returns the rows that appear in both results. Which cities have both customers and orders?

SQL
SELECT city FROM customers
INTERSECT
SELECT c.city
FROM orders AS o
JOIN customers AS c ON c.id = o.customer_id
ORDER BY city;
Text
   city    
-----------
 Lagos
 Leeds
 Lyon
 Madrid
 Pune
 Seattle
 Singapore
(7 rows)

Every city except Austin and Mumbai, whose customers haven’t ordered yet.

EXCEPT: in the first, not the second

EXCEPT returns rows from the first result that don’t appear in the second — the set difference. Product ids that have never been ordered:

SQL
SELECT id FROM products
EXCEPT
SELECT product_id FROM order_items;
Text
 id 
----
 11
(1 row)

Order matters: A EXCEPT B is not B EXCEPT A. (Oracle calls this operator MINUS.)

EXCEPT shines when comparing two whole rows, column by column. Suppose you’ve imported a new price list and want to see which products’ prices differ from it:

SQL
SELECT id, price FROM products WHERE category_id = 2
EXCEPT
SELECT id, price FROM (VALUES (4, 18.00), (5, 9.95), (6, 12.75), (7, 8.50)) AS new_prices(id, price)
ORDER BY id;
Text
 id | price 
----+-------
  5 |  9.50
  7 |  8.00
(2 rows)

Products 5 and 7 have different prices in the new list. Unlike = in a join, set operations treat two NULLs as equal, which makes them handy for “has anything changed?” comparisons on columns that can be NULL.

Set operations versus joins and EXISTS

Many questions can be answered either way:

Question Set operation Alternative
In A and in B INTERSECT JOIN, or WHERE EXISTS
In A but not B EXCEPT WHERE NOT EXISTS, or LEFT JOIN … IS NULL
A and B together UNION [ALL] — (no real alternative)

The set operations compare only the columns you select and return just those columns. NOT EXISTS can return any columns of A while matching on just a key. So: EXCEPT for “which of these values are missing?”, NOT EXISTS for “which of these rows have no match?”.

Precedence and brackets

When you chain several set operations, INTERSECT binds tighter than UNION and EXCEPT, which are evaluated left to right. Use brackets to be explicit:

SQL
(SELECT city FROM customers WHERE country = 'India'
 UNION
 SELECT city FROM customers WHERE country = 'USA')
EXCEPT
SELECT c.city FROM customers AS c
JOIN orders AS o ON o.customer_id = c.id
ORDER BY city;
Text
  city  
--------
 Austin
 Mumbai
(2 rows)

Indian and American cities, minus the ones with orders — again Austin and Mumbai.

Tip: to debug a set operation, run each query on its own and check its columns line up. A surprising number of errors come from columns listed in a different order in the two halves — (name, city) on top and (city, name) below is perfectly legal, and perfectly wrong.

Exercise

Cities and contacts

Two tasks. First, using EXCEPT, list the cities where Bean & Leaf has customers but no customer in that city has ever placed an order, sorted alphabetically (you should get Austin and Mumbai). Second, build one directory of everyone the company knows: customers (their first and last name joined with a space) and employees (their name), in a column called person, with a second column role that says 'customer' or 'employee'. Use UNION ALL and sort by person.

SQL
-- 1. Cities with customers but no orders
SELECT city FROM customers
-- EXCEPT ...

-- 2. Everyone: customers and employees

Summary

  • UNION stacks the rows of two queries and removes duplicates; UNION ALL keeps every row and is faster.
  • INTERSECT returns rows that appear in both results; EXCEPT returns rows in the first result that aren't in the second.
  • Each query must return the same number of columns, in the same order, with compatible types.
  • Column names come from the first query, and a single ORDER BY at the end sorts the combined result.
  • Set operations compare whole rows, and treat two NULLs as equal.