Concept · Advanced SQL

EXCEPT

EXCEPT returns the rows from the first SELECT that do not appear in the second. By default it removes duplicates.

EXCEPT example

SQL
SELECT id
FROM customers
EXCEPT
SELECT customer_id
FROM orders
ORDER BY id;

The first query collects every customer id; the second collects the ids that appear in orders. Taking away the second result leaves customers 6 and 12.

Check the result with small data

Three students enrolled and two passed.

Self-contained query · SQLite
WITH enrolled(name) AS (VALUES ('Amy'),('Liam'),('Eva')),
     approved(name) AS (VALUES ('Amy'),('Eva'))
SELECT name FROM enrolled
EXCEPT SELECT name FROM approved;
Query result
name
Liam

EXCEPT returns the names that are in the first set but not in the second. The operation does not change any table.

Check your understanding: What would happen if Liam passed as well?

Show answer

The result would be empty: every enrolled student would also be in approved and EXCEPT would leave no names.

What changes from case to case

The queries must be compatible as sets:

  • return the same number of columns;
  • put data of compatible types in the same positions;
  • compare equivalent concepts, even if the original names differ.
Structure
first_query
EXCEPT
second_query
ORDER BY column_name;

The ORDER BY at the end sorts the whole result. The column names are normally taken from the first query.

Common mix-ups with EXCEPT

Using columns that represent different things

Meaningless query
SELECT id FROM customers
EXCEPT
SELECT id FROM orders;

Both columns are called id, but one identifies customers and the other identifies orders. The correct comparison uses orders.customer_id.

Comparing whole sets or comparing identities

The operator compares the columns you select, not some identity implied by the table name. If one query returns an id and an email and the other returns the same id with an updated email, the two rows are different. To find people who are missing, compare their ids first; to detect full changes, decide which attributes belong in the comparison.

The plain form of EXCEPT removes duplicates. If the left set contains id 8 three times and the right set does not contain it, the result has a single row with 8. That answers a membership question, not a reconciliation of quantities. To investigate how many times rows occur, count the occurrences per key or use a variant that keeps duplicates where your engine supports one.

Nulls in set operations do not behave the way an ordinary comparison with =would suggest. Two rows with nulls in the same position can count as equal when duplicates are removed. Check that case if you are looking for incomplete records. Also check type compatibility and text collation: comparing text codes means deciding how to treat capitals, accents and spaces, on top of the SQL operation itself.

Technical questions: PostgreSQL: SELECT, columns and aliases (opens in a new tab).