Sub topic 11
INTERSECT ALL and EXCEPT ALL
This chapter assumes you know how UNION, INTERSECT, and EXCEPT behave. It also assumes you know that the plain forms remove duplicate rows and treat NULLs as equal. It covers the two variants that keep duplicates and count them: INTERSECT ALL and EXCEPT ALL.
Sets versus multisets
A table can hold the same row many times. A collection that allows repeats is a multiset (also called a bag). The plain operators convert both inputs to sets first. Only the distinct rows take part in the operation.
The ALL variants keep the repeats. Each distinct row is matched by how many times it occurs on each side. Suppose a row appears m times in the first result and n times in the second. The output contains that row this many times:
| Operator | Copies of the row in the output |
|---|---|
| `UNION ALL` | m + n |
| `INTERSECT ALL` | the smaller of m and n |
| `EXCEPT ALL` | m − n, or 0 if that is negative |
| `UNION` | 1 if m + n > 0 |
| `INTERSECT` | 1 if both m > 0 and n > 0 |
| `EXCEPT` | 1 if m > 0 and n = 0 |
You already know UNION ALL. The new part is that INTERSECT ALL and EXCEPT ALL do arithmetic on the counts. The plain EXCEPT only asks whether the second side has the row at all.
A worked example
The examples use PostgreSQL syntax. A warehouse records what it received and what it shipped, one row per unit.
CREATE TABLE received (sku text);
CREATE TABLE shipped (sku text);
INSERT INTO received (sku) VALUES
('A'), ('A'), ('A'), ('B'), ('B'), ('C'), (NULL), (NULL);
INSERT INTO shipped (sku) VALUES
('A'), ('B'), ('B'), ('B'), (NULL);Counts per value:
| sku | received (m) | shipped (n) |
|---|---|---|
| A | 3 | 1 |
| B | 2 | 3 |
| C | 1 | 0 |
| NULL | 2 | 1 |
INTERSECT ALL
SELECT sku FROM received
INTERSECT ALL
SELECT sku FROM shipped;The result has one A (min of 3 and 1), two B rows (min of 2 and 3), no C, and one NULL (min of 2 and 1). The rows come back in no guaranteed order:
A
B
B
NULLEach shipped unit is paired with at most one received unit of the same SKU. Pairs that find a partner appear in the output. The plain INTERSECT would return only A, B, and NULL, each once.
EXCEPT ALL
SELECT sku FROM received
EXCEPT ALL
SELECT sku FROM shipped;The result:
A
A
C
NULLThree A units were received and one was shipped, so two remain. B was received twice and shipped three times. The subtraction stops at zero, so B does not appear. C was never shipped. One of the two NULL units has a match, so one remains.
Now compare the plain form:
SELECT sku FROM received
EXCEPT
SELECT sku FROM shipped;This returns only C. Every other value appears at least once in shipped, so it is removed completely. Plain EXCEPT cannot tell you that two A units are unaccounted for. EXCEPT ALL can.
Direction still matters
Swap the two queries and the result changes:
SELECT sku FROM shipped
EXCEPT ALL
SELECT sku FROM received;This returns a single B. That is the one unit shipped beyond what was received. Reading both directions gives a full reconciliation: the first query shows surplus received stock, and the second shows over-shipment.
NULLs
NULLs behave the same way as in the plain operators. Two NULLs count as the same value for matching. In the example, the two NULL rows in received and the one NULL row in shipped form a group. INTERSECT ALL returns one NULL and EXCEPT ALL returns one NULL. This differs from = comparisons, where NULL = NULL is not true. Chapter material on join and EXISTS rewrites showed the same trap. It matters even more here, because a rewrite that quietly drops NULL rows changes the counts.
Checking that two tables hold the same bag of rows
A common use of EXCEPT ALL is a test for table equality that respects duplicates. Two tables hold the same multiset of rows exactly when both differences are empty:
SELECT 'only in received' AS side, sku
FROM (
SELECT sku FROM received
EXCEPT ALL
SELECT sku FROM shipped
) AS a
UNION ALL
SELECT 'only in shipped' AS side, sku
FROM (
SELECT sku FROM shipped
EXCEPT ALL
SELECT sku FROM received
) AS b;If this returns no rows, the tables match including repeat counts. The plain EXCEPT version can pass when the counts differ. For example, {A, A} and {A} look equal to it. Use ALL for data migration checks, regression tests on query output, and ledger reconciliation.
Precedence and mixing variants
ALL is a property of each operator, not of the whole statement. You can mix them:
SELECT sku FROM received
EXCEPT ALL
SELECT sku FROM shipped
UNION
SELECT sku FROM received;Here EXCEPT ALL keeps duplicates and UNION removes them from the combined result. Precedence rules are the same as without ALL. In the SQL standard, INTERSECT binds tighter than UNION and EXCEPT. Some systems evaluate set operators strictly left to right, so use parentheses when the order matters.
(SELECT sku FROM received
EXCEPT ALL
SELECT sku FROM shipped)
UNION ALL
(SELECT sku FROM shipped
EXCEPT ALL
SELECT sku FROM received);The two parenthesized differences are evaluated first, and UNION ALL joins them. This is the symmetric difference of the two bags.
A single ORDER BY after the last query sorts the combined result, as with the plain operators:
SELECT sku FROM received
EXCEPT ALL
SELECT sku FROM shipped
ORDER BY sku;Emulating the ALL variants
Some databases do not support INTERSECT ALL or EXCEPT ALL. You can rebuild them with a window function. Number the repeats of each value on each side, then apply the plain operator to the pair (value, number). A value with m copies becomes m distinct rows, numbered 1 to m. The plain operators then compare those numbered rows, and that gives the count arithmetic.
-- Emulates: received EXCEPT ALL shipped
SELECT sku
FROM (
SELECT sku, ROW_NUMBER() OVER (PARTITION BY sku ORDER BY sku) AS n
FROM received
EXCEPT
SELECT sku, ROW_NUMBER() OVER (PARTITION BY sku ORDER BY sku) AS n
FROM shipped
) AS t;Walk through A. In received the rows are (A,1), (A,2), (A,3). In shipped the only row is (A,1). EXCEPT removes (A,1) and keeps (A,2) and (A,3). That gives two A rows, which matches 3 − 1. For B, received has (B,1) and (B,2), and shipped has (B,1), (B,2), and (B,3). Nothing is left, matching max(2 − 3, 0). PARTITION BY puts NULLs in one group, so NULL counts also match.
For INTERSECT ALL, replace EXCEPT with INTERSECT in the same query. The result is (A,1), (B,1), (B,2), (NULL,1), which projects to A, B, B, NULL.
If your table has several columns, put all of them in PARTITION BY and in the select lists.
Support across databases
Support for the ALL variants is uneven, and it changes between versions. Check your version's documentation before relying on them.
| System | INTERSECT ALL / EXCEPT ALL |
|---|---|
| PostgreSQL | Supported |
| MySQL | Supported in versions that have INTERSECT and EXCEPT (8.0.31 and later) |
| SQL Server | Not supported. Use the window-function emulation. |
| SQLite | Not supported. Use the window-function emulation. |
| Oracle | Uses `MINUS` in older releases, with no `ALL` form. Recent releases add `EXCEPT` and `ALL` variants, so check your release. |
If a database rejects ALL after INTERSECT or EXCEPT, it usually reports a syntax error near the ALL keyword. That error is the signal to switch to the emulation.
Performance
ALL skips the step that discards duplicates, but the operator still has to count occurrences. Databases commonly implement these operators by sorting both inputs or by building a hash table with a counter per distinct row. Either way, memory use or sort cost grows with the number of rows. The extra cost of ALL over the plain form is usually small. The emulation costs more, because it adds a window function over each input, which normally requires a sort or a hash per partition.
Two practical points follow:
- Use
ALLwhen you need the counts. Do not use it as a shortcut for speed, since the results differ whenever duplicates exist. - On large tables, select only the columns you compare. Wider rows mean more memory for the hash table or sort.
Common errors
- Expecting
EXCEPT ALLto behave likeEXCEPTwhen the second table has repeats. Surplus rows on the second side never produce negative counts, and they never remove more than the first side contains. - Forgetting that the order of operands matters.
A EXCEPT ALL BandB EXCEPT ALL Aanswer different questions. - Mixing up
UNION ALLandINTERSECT ALLcounts. The first adds counts, and the second takes the minimum. - Using the emulation with a
ROW_NUMBERthat is not partitioned by every compared column. The numbering then runs across different values and the match breaks.
Exercise
Table x contains the values 1, 1, 1, 2, NULL, NULL. Table y contains the values 1, 2, 2, NULL. What do SELECT v FROM x INTERSECT ALL SELECT v FROM y and SELECT v FROM x EXCEPT ALL SELECT v FROM y return, ignoring row order?
Show answer
INTERSECT ALL takes the smaller count for each value. The value 1 has counts 3 and 1, so one 1. The value 2 has counts 1 and 2, so one 2. NULL has counts 2 and 1, so one NULL. The result is 1, 2, NULL. EXCEPT ALL computes the first count minus the second, with a floor of zero. The value 1 gives 3 − 1 = 2 rows. The value 2 gives max(1 − 2, 0) = 0 rows. NULL gives 2 − 1 = 1 row. The result is 1, 1, NULL.
Exercise
Your database does not support EXCEPT ALL. Write a query that returns the rows of received that are left over after removing one matching row per row of shipped, using ROW_NUMBER and plain EXCEPT.
Show answer
SELECT sku FROM (SELECT sku, ROWNUMBER() OVER (PARTITION BY sku ORDER BY sku) AS n FROM received EXCEPT SELECT sku, ROWNUMBER() OVER (PARTITION BY sku ORDER BY sku) AS n FROM shipped) AS t; The numbering turns each copy of a value into a distinct row, so plain EXCEPT removes exactly as many copies as the second side has.