Knowledge base / SQL

SQL EXCEPT: set difference, duplicates and NULL

EXCEPT compares the complete selected rows. I explain comparison direction, subtracting copies, and why a changed name does not prove that a customer disappeared.

Kajo RudzińskiPublished Updated 4 min read

Two trays of blocks compared by a sorting gate, with an unmatched block remaining in a separate tray, in yellow and navy pixel art.

When comparing two exports, I first establish what a difference means. Are we looking for identifiers present only in the first file, changed customer attributes, or missing copies of an event? EXCEPT compares query results, but the selected columns and operator variant determine the answer we receive.

Comparison direction and selected columns

PostgreSQL describes EXCEPT as a difference between query results: rows from the left result that are absent from the right, with duplicate removal by default. For two tables containing an integer customer_id, I can write:

SELECT customer_id
FROM previous_customers
EXCEPT
SELECT customer_id
FROM current_customers
ORDER BY customer_id;

This compares identifiers in previous and current exports. Reversing the tables answers a different question: which IDs appear only in the current file? For a complete comparison, I would consider both directions and label them explicitly. A single set difference is not symmetric.

Both queries must return the same number of columns with compatible types at corresponding positions. I would avoid SELECT *: a changed table layout can alter the comparison or cause an error. For text, comparison rules and the engine’s collation also need consideration. Matching column names alone does not establish the intended comparison.

Small data: EXCEPT and EXCEPT ALL

Assume two synthetic tables, left_ids and right_ids, each with one integer column named id. Repetitions are intentional. NULL means a missing value, rather than a text label consisting of four letters.

Table Contents of id, retaining the number of copies
left_ids 10, 10, 10, 20, 20, NULL
right_ids 10, 30, NULL

Without ALL, the query is:

SELECT id FROM left_ids
EXCEPT
SELECT id FROM right_ids;

The result has one row containing 20. Ten appears on both sides and disappears from the difference. The two copies of 20 become one. The two missing values also match for this set comparison; Microsoft documents that NULL rule. This differs from using ordinary equality in a filtering condition.

In PostgreSQL, I can preserve the meaning of multiplicity:

SELECT id FROM left_ids
EXCEPT ALL
SELECT id FROM right_ids
ORDER BY id;

Now the output is 10, 10, 20, 20. For ten, we subtract one right-side copy from three left-side copies. Twenty has two copies on the left and none on the right. Each side has one missing value, leaving no NULL copy in the result.

PostgreSQL gives the rule as max(m - n, 0). We subtract occurrence counts. A value that appears on the right can therefore still remain under EXCEPT ALL when it appears more often on the left. More copies on the right never produce a negative row count.

Repeated stacks of blocks, showing unique remaining items separately from the copies left after subtraction.

Support depends on engine and version

Engine EXCEPT EXCEPT ALL
PostgreSQL 18 yes yes
MySQL since 8.0.31, including 8.4 yes yes
SQL Server yes no
SQLite yes no
Oracle Database 21c yes, also named MINUS yes, also MINUS ALL

The MySQL 8.0.31 release notes confirm when support was added, while the MySQL 8.4 manual documents the syntax. The old claim that MySQL has no EXCEPT support now leads readers to unnecessary workarounds.

SQLite provides difference with duplicate removal, without EXCEPT ALL. The Oracle 21c manual includes EXCEPT and the ALL variants. For an older Oracle deployment, I would check its version rather than assume the same list of operators.

A changed name does not establish customer departure

Suppose the previous export contains (7, 'Company A') and the current one contains (7, 'Company B'). Comparing customer_id, name returns the old pair in the difference. This establishes that the exact pair is absent from the second result. It does not establish that customer ID 7 disappeared.

I would select the identifier alone to check presence, then assess attribute changes separately under an agreed comparison rule. Even an absent ID does not automatically establish customer departure: an export might use another filter, period or refresh time. The operator determines a data difference; interpreting that difference still requires context.

NOT EXISTS needs a deliberate comparison

For our single field, a PostgreSQL equivalent of ordinary EXCEPT can be written as:

SELECT DISTINCT l.id
FROM left_ids AS l
WHERE NOT EXISTS (
    SELECT 1
    FROM right_ids AS r
    WHERE r.id IS NOT DISTINCT FROM l.id
)
ORDER BY l.id;

DISTINCT removes left-side copies, while IS NOT DISTINCT FROM also matches two missing values. NOT EXISTS selects cases without a matching subquery row. Ordinary equality, r.id = l.id, does not match two NULL values. Ignoring both differences can make a simple anti-join return repeated values and a missing value that are absent from the EXCEPT result.

I would not treat this expression as a universal recipe for every engine version. Before choosing an alternative, I would check null-safe comparison syntax and the required output multiplicity. I also make no claim that one approach is always faster. That needs assessment of the particular query, data and plan.

Exercise

Add another ten to right_ids in your mental example. Ordinary EXCEPT still returns only 20. Under EXCEPT ALL, one ten and two twenties remain. Then reverse the ordinary comparison: the result is 30. For the intersection of the results instead, continue with INTERSECT.

Key takeaways

Does MySQL support EXCEPT?

Yes, since MySQL 8.0.31, including ALL. Earlier versions need a different expression chosen for the intended duplicate and NULL behaviour.

Does SQLite support EXCEPT ALL?

SQLite supports EXCEPT with duplicate removal, but has no EXCEPT ALL form. Do not transfer that PostgreSQL variant unchanged into SQLite.

Does EXCEPT compare records by their key?

It compares all selected columns by position. Selecting ID and name makes a changed name a different row even when ID is unchanged. Select only ID when checking for missing identifiers.

AI was used in an automated way while working on this article. If you want to learn how to do it too, check out this project.

Kajo Rudziński

Newsletter KajoData

Let’s keep in touch.

I write about data analysis, learning and changing careers. My newsletter and the sign-up form are in Polish. If that works for you, I’d be glad to see you there.