Skip to content
Back to 50 Concepts
Topic 14 of 50query-executionIntermediate

# Topic 14: IN & NOT IN

Discrete set matching, subquery execution, and the catastrophic Three-Valued Logic trap of NOT IN with NULLs.

1. Definition

The IN operator determines whether a specified value matches any value within a discrete list or subquery set.

Relational Invariant:Deterministic relational algebra contract evaluated by the Cost-Based Optimizer.

2. Explain Like I'm 5

Intuitive mental model for beginners

IN is like a guest list with multiple names. If your name is on any of the lines, you get in. NOT IN means you can only enter if you are not on that list.

3. Animation & Visual Simulation

Interactive Engine Trace
Interactive Engine Simulation

IN & NOT IN Visual Simulator

Step 1 of 3
SQL>SELECT * FROM users WHERE role IN ('admin', 'editor', 'manager');Active Input

Step 1: Input & Parsing Stage

Engine Action: Validate SQL syntax and resolve schema metadata for IN & NOT IN
SQL Input

Initiating IN & NOT IN

Schema Catalog

Checking Table Invariants

How the Database Executes This:

The database engine inspects active tables, verifies permissions, and prepares the physical operation.

💡 VIP Guest List: IN checks if you are on the list; NOT IN tries to confirm you are not on the list, but if a name on the list is smudged/unknown (NULL), security stops everyone.

4. Real-World Example

Selecting users whose billing country is in North America.

Users
idnamecountry_code
1AliceUS
2BobCA
3CharlieIN
Relational walkthrough: country_code IN ('US', 'CA', 'MX') matches Alice and Bob.

5. SQL Syntax

ANSI SQL / PostgreSQL Dialect
Step 1: Discrete list membership
SELECT id, name, country_code
FROM users
WHERE country_code IN ('US', 'CA', 'MX');
Syntactic sugar for country_code = 'US' OR country_code = 'CA' OR country_code = 'MX'.
Step 2: Dynamic subquery with NOT EXISTS (safe vs NOT IN)
SELECT u.id, u.name
FROM users u
WHERE NOT EXISTS (
  SELECT 1 FROM blacklisted_users b WHERE b.user_id = u.id
);
Safely handles NULL values without dropping all records.

6. Important Rules & Behaviors

RuleBehavioral Explanation
List Matchingval IN (x, y, z) evaluates to TRUE if val equals any element in the set.
NOT IN with NULL DisasterIf the set contains even a single NULL value, NOT IN evaluates to UNKNOWN for all rows, returning 0 rows!
Subquery FormOptimizers transform IN (SELECT ...) into Semi-Joins; NOT IN into Anti-Joins.
Three-Valued Logic NULL catastropheIf the list inside NOT IN contains a single NULL value, the entire expression evaluates to UNKNOWN for all rows.
Optimizer array transformEngines transform IN (constants) into an index seek list (ScalarArrayOp) for O(K * log N) lookups.

7. Deep Dive: The Infamous NOT IN with NULL Trap

In SQL: val NOT IN (1, 2, NULL) is evaluated as: val != 1 AND val != 2 AND val != NULL. Because val != NULL evaluates to UNKNOWN, and anything AND UNKNOWN cannot evaluate to TRUE, the entire WHERE clause returns ZERO rows!

-- DANGEROUS: If blacklist contains even ONE NULL, returns 0 rows!
SELECT * FROM users WHERE id NOT IN (SELECT user_id FROM blacklist);

-- SAFE: NOT EXISTS handles NULLs deterministically:
SELECT * FROM users u WHERE NOT EXISTS (
  SELECT 1 FROM blacklist b WHERE b.user_id = u.id
);
Caution: Never use NOT IN with a subquery unless the subquery column is strictly guaranteed to be NOT NULL.

8. Advantages & Disadvantages

Advantages

  • •Concise syntax compared to chaining dozens of OR statements.
  • •Optimizer can leverage B-Tree index scans with multi-point skips.

Disadvantages & Trade-offs

  • •NOT IN combined with NULL subqueries causes silent query failure.

9. Common Interview Questions

Q1.Why does "val NOT IN (1, 2, NULL)" always return zero rows in SQL? Explain Three-Valued Logic.

NOT IN is expanded as: val != 1 AND val != 2 AND val != NULL. In SQL, any comparison with NULL (val != NULL) evaluates to UNKNOWN. In boolean logic: TRUE AND TRUE AND UNKNOWN evaluates to UNKNOWN. Because the WHERE clause only accepts rows where the condition is TRUE, every single row is rejected! If a subquery returns even one NULL, NOT IN silently returns empty set. Use NOT EXISTS instead.

Q2.What is the performance difference between IN (list of 10,000 values) vs JOIN with a temporary table?

Passing 10,000 literal constants inside an IN (...) clause causes massive SQL query string bloat, slows down parser tokenization, prevents query plan caching, and can exceed query buffer limits. The production standard is passing an array (ANY(?)) or bulk inserting values into a temporary table and performing an INNER JOIN, which uses hash joins or merge joins in O(N).

Q3.How does the query optimizer execute IN (subquery) vs EXISTS (subquery)?

Historically, naive engines executed IN (subquery) as a nested loop for every row. Modern Cost-Based Optimizers (PostgreSQL, MySQL 8+) automatically rewrite IN (subquery) into a Semi-Join or Hash Join. However, when nullable columns are involved, the optimizer cannot easily rewrite NOT IN into an Anti-Join due to 3VL rules, making NOT EXISTS strictly superior.

Q4.What is the PostgreSQL ANY(ARRAY[...]) syntax and why is it preferred over IN?

In PostgreSQL, WHERE id = ANY($1::int[]) is preferred over WHERE id IN (...) when using prepared statements. It allows passing a single array parameter from application code (e.g. Node.js or Go) without dynamically constructing comma-separated SQL strings, eliminating SQL injection risk and enabling 100% prepared statement cache reuse.

Q5.What is the difference between IN and Multiple OR statements under the hood?

Mathematically, WHERE id IN (1, 2, 3) is equivalent to WHERE id = 1 OR id = 2 OR id = 3. However, under the hood, the optimizer recognizes IN as a discrete set lookup and executes it as an Index Scan using a ScalarArrayOp seek list, whereas arbitrary OR expressions across multiple columns require complex BitmapOr scans.

10. Interview-Ready Answer

“The IN operator matches values against a discrete set. While IN is clean, NOT IN poses a severe production risk when NULLs are present in the dataset. Production queries should use NOT EXISTS to guarantee predictable two-valued logic.”

11. Quick Test

Scenario Question:

What does the query "SELECT 1 WHERE 5 NOT IN (1, 2, NULL);" return?

Select your answer: