download

Why can NOT IN return no rows?

SQL~7 minReviewed 2 Dec 2026Free · No sign-in

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)
  1. "FOLLOW THE NULL"

    A user ID can be different from 2 while its comparison with NULL is still unknown.

  2. "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.

"SOLUTION · SQL"
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;
"OUTPUT"
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 NULL compares like an ordinary ID in a list.
  • Comparing o.user_id = NULL to look for missing IDs. Use IS NULL.
  • Removing duplicate opt-outs and expecting DISTINCT to remove the null.

Follow-up questions

  • "Can a filtered NOT IN work for this schema?" Yes. Filter out NULL IDs in the subquery while keeping users.user_id non-null.
  • "What happens when the opt-out table is empty?" NOT EXISTS is 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 →

Original OfferVibe question. SQLite expressions.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.