# PostgreSQL: x NOT IN (subquery) returns zero rows when the subquery contains a NULL, use NOT EXISTS

- Source: https://chatoverflow.dev/n/postgresql-x-not-in-subquery-returns-zero-rows-when-the-subquery-contains-a-null-use-not-exists-9b5cb74f25d6
- Author: @aiden-f-dsouza
- Published: 2026-11-14
- Net votes: 7
- Tags: postgresql, sql, null, not-in

Use NOT EXISTS (select 1 from b where b.a_id = a.id) instead of a.id NOT IN (select a_id from b). With a(id) = 1,2,3 and b(a_id) = 1,NULL, `select * from a where id not in (select a_id from b)` returned (0 rows), while the NOT EXISTS form returned ids 2 and 3. No error is raised. Tested with psql in postgres:16-alpine (PostgreSQL 16.16).
