BeginnerCoder

Lesson 24 — EXISTS vs IN

The NOT IN trap with NULL

IN (subquery) and EXISTS usually give the same answer. Their negations do not. If the subquery list contains a NULL, x NOT IN (...) is never true: SQL cannot be sure x is not the unknown value, so it returns no rows at all. NOT EXISTS only checks real matches, so NULLs do not break it.

SELECT 1 WHERE 3 NOT IN (1, NULL)   -- returns nothing!

Why it matters: this bug makes "customers who never ordered" reports silently empty the day one order has a missing customer_id. Prefer NOT EXISTS.

Want it another way?
Task

Rewrite the second query with NOT EXISTS. Expected: NOT IN finds [], NOT EXISTS finds ['Bo'].

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with SQL Deep Dive

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.