← Homepage

EXISTS vs IN / NOT IN

October 11, 2026

Author: Daniel Jordan Viray

SQL notes · clinical toy data · the NULL trap that empties your result

The idea. Three ways to ask "which patients have a matching row in another table?" EXISTS and IN usually agree. But NOT IN has a trap: a single NULL in the subquery list silently wipes out the entire result — no error, no warning.

Toy data

patients

patient_idname
1Alice
2Bob
3Carol
4Dave

prescriptions — note rx 103: paper script, patient never linked (NULL)

rx_idpatient_iddrug
1011atorvastatin
1022metformin
103NULLatorvastatin
1041lisinopril

Who has at least one prescription?

With EXISTS — "is there at least one matching row?"

SELECT name FROM patients p
WHERE EXISTS (SELECT 1 FROM prescriptions r WHERE r.patient_id = p.patient_id)
ORDER BY name;
name
Alice
Bob

Read it as a per-patient question: for Alice, is there at least one prescription row pointing at her? Yes → keep her. Correlated, but the optimizer handles it.

With IN — "is the id in this list?"

SELECT name FROM patients
WHERE patient_id IN (SELECT patient_id FROM prescriptions)
ORDER BY name;
name
Alice
Bob

Same answer. The NULL in the list doesn't hurt here: Alice and Bob match real values, and matching is all IN needs.

Who has no prescription? — the trap

SELECT name FROM patients
WHERE patient_id NOT IN (SELECT patient_id FROM prescriptions)
ORDER BY name;

empty — but Carol and Dave have no prescriptions!

name

Why empty? For Carol the database evaluates 3 NOT IN (1, 2, NULL, 1), i.e. 3<>1 AND 3<>2 AND 3<>NULL AND 3<>1 → TRUE AND TRUE AND UNKNOWN AND TRUE = UNKNOWN — and WHERE keeps only TRUE rows. One NULL poisons every candidate. In real pipelines the NULL arrives via ETL gaps, optional foreign keys, or half-linked records like rx 103.

Fix 1: filter the NULLs out of the list

SELECT name FROM patients
WHERE patient_id NOT IN (SELECT patient_id FROM prescriptions WHERE patient_id IS NOT NULL)
ORDER BY name;
name
Carol
Dave

Fix 2: NOT EXISTS — NULL-proof by construction

SELECT name FROM patients p
WHERE NOT EXISTS (SELECT 1 FROM prescriptions r WHERE r.patient_id = p.patient_id)
ORDER BY name;
name
Carol
Dave

NOT EXISTS never compares against the NULL as a value; it only asks whether a matching row exists. When the column is nullable, prefer it.

Watch out.
Prove it. Every query on this page was run against SQLite and the tables show actual output — not hand-typed guesses.