Falle
NOT IN mit einem NULL
Ein einziges NULL in der Liste, und
NOT IN liefert überhaupt keine Zeilen.x NOT IN (1, NULL) ist x <> 1 AND x <> NULL, und x <> NULL ist unbekannt, nie wahr. Verwenden Sie
NOT EXISTS oder fügen Sie der Unterabfrage WHERE col IS NOT NULL hinzu.
Die Falle
WITH excluded(city) AS (VALUES ('Paris'), (NULL))
SELECT COUNT(*) AS customers
FROM customers
WHERE city NOT IN (SELECT city FROM excluded);
| customers |
|---|
| 0 |
Die Korrektur
WITH excluded(city) AS (VALUES ('Paris'), (NULL))
SELECT COUNT(*) AS customers
FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM excluded e WHERE e.city = c.city);
| customers |
|---|
| 348 |