EXCEPT and EXCEPT ALL: compare differences
Overview
EXCEPT returns distinct rows in the first result that are absent from the second. It is directional. EXCEPT ALL in PostgreSQL subtracts right-side occurrences from left-side occurrences, with a minimum result multiplicity of zero.
First example
SELECT v FROM set_aEXCEPTSELECT v FROM set_bORDER BY v NULLS LAST;Observed SQLite result (rows in JSON):
[ [ 2 ]]How it works
With the fixture, distinct EXCEPT returns 2, whereas EXCEPT ALL returns one 1 and one 2. The NULL from the first input is removed by a NULL in the second input. Reversing the inputs gives 3 for ordinary EXCEPT. In the shop query, subtract purchased product IDs from all product IDs to find Pencil (4). EXCEPT removes duplicates from the left, while NOT EXISTS may preserve repeated left rows; nullable keys also need deliberate matching semantics. SQLite 3.46.1 rejects EXCEPT ALL. Oracle MINUS is a related dialect spelling of distinct difference; Oracle runtime and version-specific variants are outside this batch.
Practical example
SELECT id FROM productsEXCEPTSELECT product_id FROM order_itemsORDER BY id;Observed SQLite result (rows in JSON):
[ [ 4 ]]Practice and mistakes
Practice: reverse set_a and set_b to predict the new distinct difference, then check it. Find customers without orders using EXCEPT and compare with NOT EXISTS from the previous chapter. Do not assume that EXCEPT ALL and EXCEPT return the same number of rows.
PostgreSQL 17 example — NOT RUN
SELECT v FROM set_aEXCEPT ALLSELECT v FROM set_bORDER BY v NULLS LAST;Expected result, not executed: [[1], [2]]