Skip to main content
PostgreSQL & Redis Engineering Predict Output P0 Medium

NULL in NOT IN vs NOT EXISTS and LEFT JOIN filters

Given users(id): (1),(2) and banned(user_id): (2),(NULL), what does Query A return vs Query B?

Official Reference

Code Snippet

-- Query A
SELECT id FROM users WHERE id NOT IN (SELECT user_id FROM banned);

-- Query B
SELECT u.id FROM users u WHERE NOT EXISTS (
  SELECT 1 FROM banned b WHERE b.user_id = u.id
);

Expected Output & Explanation

Query A: 0 rows (empty)
Query B: 1 row (id = 1)

In SQL three-valued logic, 1 NOT IN (2, NULL) evaluates to (1 <> 2) AND (1 <> NULL) -> TRUE AND UNKNOWN -> UNKNOWN, so WHERE filters out every row! NOT EXISTS tests only whether matching rows exist and safely returns user 1.

Follow-up Interview Question · What happens if you put a filter on the right table of a LEFT JOIN inside WHERE instead of ON?

Module Context & References

SQL & PostgreSQL · Query behavior & trap drills Predict query results for NULL logic, JOIN filters, aggregates and window functions
Personal Notes · Markdown

Technologies & Interview Topics Covered

Switch between short-term interview tracks and long-term 80/20 engineering depth to practice JavaScript internals, React rendering and hooks, timed frontend machine coding UI challenges, MeetaPro FG300, Blind 75 & NeetCode 150 DSA patterns, Python & FastAPI APIs, PostgreSQL query optimization & MVCC, Redis caching, Applied AI RAG pipelines & evaluations, and distributed system design.