Why can NOT IN return no rows?
Question
List users who have no opt-out row for their ID. User IDs in the users table are non-null. An opt-out row with a NULL user ID has no effect on any user. Explain why filtering with NOT IN against the entire table can return an empty result. Sort by user ID.
users
| user_id |
|---|
| 1 |
| 2 |
| 3 |
opt_outs
| user_id |
|---|
| 2 |
| NULL |
| 2 |
Show hints (2)
- "FOLLOW THE NULL"
A user ID can be different from 2 while its comparison with
NULLis still unknown. - "ASK ABOUT EXISTENCE"
Check whether each user has any opt-out row whose ID equals their own.
Show checked explanation
Use NOT EXISTS with a match on the user ID. With NOT IN, the NULL makes the test unknown for otherwise unmatched IDs, and WHERE keeps only true results.
SELECT u.user_id FROM users AS u WHERE NOT EXISTS ( SELECT 1 FROM opt_outs AS o WHERE o.user_id = u.user_id ) ORDER BY u.user_id;
user_id 1 3
Ran the query on SQLite 3.49 with the sample rows and edge cases.
Walkthrough
The opt-out rows match only user 2. A comparison between NULL and a user ID is unknown, so that row never satisfies the inner equality. With NOT IN, users 1 and 3 have no equal value but still face an unknown comparison. Neither row passes the outer filter.
Common mistakes
- Assuming
NULLcompares like an ordinary ID in a list. - Comparing
o.user_id = NULLto look for missing IDs. UseIS NULL. - Removing duplicate opt-outs and expecting
DISTINCTto remove the null.
Follow-up questions
- "Can a filtered NOT IN work for this schema?" Yes. Filter out
NULLIDs in the subquery while keepingusers.user_idnon-null. - "What happens when the opt-out table is empty?"
NOT EXISTSis true for every user, because the subquery finds no matches.
What a strong answer covers
Distinguish unknown comparisons from the existence of a matching row and state how nullable IDs affect both forms.
Open in interactive practice deck →