October 11, 2026
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.
patients
| patient_id | name |
|---|---|
| 1 | Alice |
| 2 | Bob |
| 3 | Carol |
| 4 | Dave |
prescriptions — note rx 103: paper script, patient never linked (NULL)
| rx_id | patient_id | drug |
|---|---|---|
| 101 | 1 | atorvastatin |
| 102 | 2 | metformin |
| 103 | NULL | atorvastatin |
| 104 | 1 | lisinopril |
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.
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.
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.
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 |
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.
NOT IN + any NULL in the subquery = silently empty result. The #1 real-world gotcha.IN with a NULL in the list is safe for matches — the asymmetry between IN and NOT IN is the lesson.NOT IN query returns nothing and you expected rows, check the subquery for NULLs first.