Sub topic 6
EXCEPT: rows in the first result but not the second
This chapter covers the EXCEPT operator. It assumes you can write basic SELECT queries with WHERE, that you know what DISTINCT does, and that you have read the earlier chapters on union compatibility, UNION, and INTERSECT. You should also know that NULL means "unknown or missing value".
What EXCEPT does
EXCEPT takes the rows produced by a first query and removes any row that also appears in the result of a second query. What remains is every row that is in the first result but not in the second. Duplicates among the remaining rows are removed, so the output is a set of distinct rows.
The classic use is "find what is in A but missing from B". A few examples:
- Subscribers who have not unsubscribed.
- Products that have never been ordered.
- Employees who are not assigned to any project.
Here is the basic form, using the newsletter tables from this tutorial:
SELECT email FROM newsletter_subscribers
EXCEPT
SELECT email FROM unsubscribed;The query returns the distinct emails from newsletter_subscribers that do not appear in unsubscribed.
Order matters
UNION and INTERSECT are symmetric. Swapping the two queries gives the same rows. EXCEPT is not symmetric, so swapping the queries changes the answer.
Suppose the tables contain these emails:
| Table | Emails |
|---|---|
| newsletter_subscribers | ann, bob, cy, dee |
| unsubscribed | bob, dee, eve |
The two directions give different results:
| Query | Result |
|---|---|
| subscribers EXCEPT unsubscribed | ann, cy |
| unsubscribed EXCEPT subscribers | eve |
The first form answers "who is still subscribed?". The second answers "who unsubscribed without ever being a subscriber?". When a result looks wrong, check the order of the two queries first.
The rules it follows
EXCEPT obeys the same compatibility rules as the other set operators.
- Both queries must return the same number of columns.
- Columns in the same position must have compatible types.
- The column names of the result come from the first query.
Rows are compared as whole rows, position by position. That means a row is removed only when every column matches. Consider this query:
SELECT email, city FROM newsletter_subscribers
EXCEPT
SELECT email, city FROM unsubscribed;A subscriber named ann in Oslo is not removed by an unsubscribed row for ann in Bergen, because the city values differ. If you want to compare on email alone, select only the email column in both queries. This is a common source of surprises when you add an extra column "just to see it". The extra column changes what counts as a match.
Duplicates and NULLs
EXCEPT removes duplicates from its output. If ann appears three times in newsletter_subscribers and not at all in unsubscribed, the result contains ann once. This is the same behavior as UNION, and it is why EXCEPT has an implicit DISTINCT step. That step costs something, as the performance section below explains.
For NULL, set operators use a different rule from the = operator. In a WHERE clause, NULL = NULL is not true, so a row with a NULL never matches another NULL. Set operators compare rows with "is not distinct from" semantics. Two NULL values are treated as equal for the purpose of matching.
Take this example, which you can run in PostgreSQL:
CREATE TEMP TABLE newsletter_subscribers (email text);
CREATE TEMP TABLE unsubscribed (email text);
INSERT INTO newsletter_subscribers VALUES ('[email protected]'), (NULL), (NULL);
INSERT INTO unsubscribed VALUES (NULL);
SELECT email FROM newsletter_subscribers
EXCEPT
SELECT email FROM unsubscribed;The result is a single row, [email protected]. The NULL in newsletter_subscribers matched the NULL in unsubscribed and was removed, and the duplicate NULL was removed along with it.
Now compare the NOT EXISTS form from earlier in the tutorial:
SELECT DISTINCT s.email
FROM newsletter_subscribers s
WHERE NOT EXISTS (
SELECT 1 FROM unsubscribed u WHERE u.email = s.email
);Here u.email = s.email is never true when s.email is NULL, so no matching row is found and NOT EXISTS is true. The NULL row survives, and the result has two rows: [email protected] and NULL. The two queries look equivalent but return different answers.
Rewriting EXCEPT with other constructs
You will often see the same idea written without EXCEPT. There are three common forms.
NOT EXISTS
This is the form shown above. It is usually the safest rewrite. Add DISTINCT to reproduce the duplicate removal. To also reproduce the NULL behavior, use a null-safe comparison. PostgreSQL offers IS NOT DISTINCT FROM:
SELECT DISTINCT s.email
FROM newsletter_subscribers s
WHERE NOT EXISTS (
SELECT 1
FROM unsubscribed u
WHERE u.email IS NOT DISTINCT FROM s.email
);With the sample data above, this query returns only [email protected], matching EXCEPT. Null-safe comparisons can prevent the database from using an index on email, so test the speed on your own data.
LEFT JOIN with IS NULL
This form is called an anti-join. It keeps rows from the left table that found no partner on the right.
SELECT DISTINCT s.email
FROM newsletter_subscribers s
LEFT JOIN unsubscribed u ON u.email = s.email
WHERE u.email IS NULL;It has the same NULL problem as NOT EXISTS. It also has a trap of its own. If you test a column that can be NULL in the right table for other reasons, you cannot tell "no match" from "matched a row whose value is NULL". Test a column that is never NULL, such as a primary key.
NOT IN
NOT IN looks tempting, but it is the most dangerous option:
SELECT DISTINCT email
FROM newsletter_subscribers
WHERE email NOT IN (SELECT email FROM unsubscribed);If the subquery returns even one NULL, NOT IN returns no rows at all. The reason is that x NOT IN (a, NULL) evaluates to unknown for every x that is not a, and WHERE keeps only rows where the condition is true. With the sample data above, unsubscribed contains a NULL, so this query returns nothing. Avoid NOT IN against a column that may contain NULL.
Choosing between them
| Situation | Better choice |
|---|---|
| Compare whole rows across several columns | `EXCEPT` |
| You need columns from the first table that are not in the comparison | `NOT EXISTS` or `LEFT JOIN` |
| Comparison columns may be `NULL` and you want them to match | `EXCEPT` |
| Comparison columns may be `NULL` and you want them not to match | `NOT EXISTS` |
| The other side may contain `NULL` | Avoid `NOT IN` |
The second row of the table is the main practical limit of EXCEPT. The output contains only the columns you select in the first query. If you also want the subscriber's name or signup date, and those do not take part in the comparison, you cannot add them without changing what counts as a match. A NOT EXISTS query handles this naturally:
SELECT s.email, s.signup_date
FROM newsletter_subscribers s
WHERE NOT EXISTS (
SELECT 1 FROM unsubscribed u WHERE u.email = s.email
);Note that this version does not remove duplicates, because signup_date may differ between duplicate emails.
Combining EXCEPT with other operators
You can chain set operators. A common pattern is to merge two lists and then subtract a third:
(SELECT email FROM customers
UNION
SELECT email FROM newsletter_subscribers)
EXCEPT
SELECT email FROM unsubscribed;The parentheses make the order explicit. Without them, the result depends on precedence rules. The SQL standard gives INTERSECT higher precedence than UNION and EXCEPT, and PostgreSQL follows it. UNION and EXCEPT have equal precedence and are evaluated left to right. Some databases, including older versions of Oracle and some others, evaluate every operator strictly from top to bottom. Write parentheses whenever a query mixes operators.
Because EXCEPT is not associative, grouping changes results. In this query, A EXCEPT B EXCEPT C means (A EXCEPT B) EXCEPT C, which removes both B and C from A. The form A EXCEPT (B EXCEPT C) returns something different, because rows of C that are in B are added back.
Sorting the result
A single ORDER BY goes after the last query and applies to the entire result:
SELECT email FROM newsletter_subscribers
EXCEPT
SELECT email FROM unsubscribed
ORDER BY email;You cannot sort the individual inputs without wrapping them in parentheses, and doing so has no lasting effect, since the operator discards the order. In many databases the ORDER BY must name columns or positions from the first query, so ORDER BY 1 also works.
EXCEPT ALL
The standard defines EXCEPT ALL, which keeps duplicates and subtracts them by count. If a row appears 3 times in the first result and 1 time in the second, EXCEPT ALL returns it 2 times. Plain EXCEPT would return it 0 times, because it appears in the second result.
SELECT email FROM newsletter_subscribers
EXCEPT ALL
SELECT email FROM unsubscribed;PostgreSQL supports EXCEPT ALL. Many other systems do not, so check your database before relying on it.
Dialect differences
- Oracle calls the operator
MINUS. Recent Oracle versions also acceptEXCEPT, but older code usesMINUS. - MySQL added
EXCEPTandINTERSECTin version 8.0.31. Before that, you had to useNOT EXISTSor an anti-join. - SQL Server supports
EXCEPTbut notEXCEPT ALL. - SQLite supports
EXCEPTbut notEXCEPT ALL.
Performance
To remove duplicates and find matches, the database usually sorts both inputs or builds a hash table. That work grows with the size of the data. Some practical points:
- Select only the columns you need. Fewer and narrower columns make the comparison cheaper.
- Filter each query with
WHEREbefore the operator runs, so fewer rows reach the comparison. - The optimizer often turns
EXCEPTinto the same anti-join plan asNOT EXISTS. When both forms are correct for your data, compare them withEXPLAINinstead of assuming one is faster.
Common mistakes
- Swapping the two queries and getting the opposite answer.
- Adding an extra column to the select list and breaking the match.
- Expecting
EXCEPTto keep duplicates. UseEXCEPT ALLwhere it exists. - Rewriting with
NOT EXISTS, a join, orNOT INwithout handlingNULL. - Mixing operators without parentheses and relying on precedence that differs between databases.
Exercise
A table orders(customer_id, ...) and a table customers(customer_id, name) are given. You want the ids of customers who have never placed an order, and orders.customer_id may contain NULL for guest checkouts. Write the query with EXCEPT, and explain why NOT IN would be a poor replacement.
Show answer
SELECT customerid FROM customers EXCEPT SELECT customerid FROM orders; This returns the distinct customer ids with no matching order. NOT IN would be a poor replacement because the subquery SELECT customerid FROM orders contains NULL for guest checkouts. With a NULL in the list, customerid NOT IN (...) is never true, so the query would return no rows at all.
Exercise
Given newsletter_subscribers containing ann, ann, bob and unsubscribed containing bob, what do EXCEPT and EXCEPT ALL each return for the query on email?
Show answer
EXCEPT returns one row, ann, because duplicates are removed and bob is subtracted. EXCEPT ALL returns two rows, ann and ann, because it keeps duplicates and subtracts one bob for one bob. The result is the same set of values, but EXCEPT ALL preserves the count of ann.