Finding rows with no match in SQL
The anti join: an outer join, then keep only the rows that failed to match.
SELECT
c.id,
c.name
FROM customers AS c
LEFT JOIN orders AS o
ON o.customer_id = c.id
WHERE o.id IS NULL;
SELECT
c.id,
c.name
FROM customers AS c
WHERE NOT EXISTS (
SELECT 1
FROM orders AS o
WHERE o.customer_id = c.id
);
How it works
LEFT JOINfills unmatched rows with NULLs on the right.WHERE right.key IS NULLkeeps exactly those unmatched rows.NOT EXISTSsays the same thing and usually plans the same way.
Keywords and builtins used here
ASEXISTSFROMISJOINLEFTNOTNULLONSELECTWHEREc
The run, in numbers
- Lines
- 17
- Characters to type
- 221
- Tokens
- 64
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 45 seconds.
Step 8 of 9 in Joins, step 16 of 22 in Joins & aggregation.