A query using NOT IN with a subquery suddenly returns zero rows even though you expect matches. What's likely going on, and how would you fix it?

technical-conceptual · Mid level · software-engineering

What the interviewer is really asking

Assesses whether the candidate understands SQL's three-valued logic — that a NULL in the NOT IN subquery makes every comparison evaluate to UNKNOWN, so no row passes the WHERE filter — and knows the standard fixes (NOT EXISTS, a LEFT JOIN anti-join, or filtering NULLs), rather than treating it as a mysterious bug.

What to say

What to avoid

Example answers

Strong: The subquery almost certainly returns a NULL. With NOT IN, the row has to be unequal to every value in the list, and any comparison to NULL is UNKNOWN, so the whole predicate is never TRUE and every row gets dropped. I'd rewrite it as NOT EXISTS with a correlated subquery, since that only yields TRUE or FALSE and ignores the NULL trap — or add IS NOT NULL to the inner query if I want the smallest change.

Weak: NOT IN can be slow on big tables, so it's probably timing out or the optimizer is choosing a bad plan. I'd add an index on the column and maybe rewrite it as a join to speed it up.

Want questions matched to your role? Paste a job title, job description, or CV and get a personalized set, or go Pro to unlock the full bank.