1. Home
  2. Blog
  3. Databases & SQL

Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

EXISTS and IN often return the same rows, until a single NULL sneaks into the data and NOT IN quietly returns nothing. Here is how both work, where they differ, and which to choose, with every query run.

10 min read
SQL EXISTS vs IN: differences, the NOT IN NULL trap and performance

Key takeaways

  • IN checks whether a value is in a list or subquery result. EXISTS checks whether a subquery returns any row.
  • For positive checks they usually give the same result, and modern optimizers often plan them the same way.
  • NOT IN returns no rows if the subquery contains a single NULL. NOT EXISTS does not have this problem.
  • Default to NOT EXISTS for “rows with no match” queries.

A report lists customers who have never placed an order. It works for months. Then a guest checkout feature starts saving orders with no customer ID, and the report suddenly shows nobody. No error, no warning, just an empty result. The cause is one of SQL’s best-known traps: NOT IN meeting a NULL.

We ran every query below in SQLite 3.50, and the results are from that run. The NULL behaviour comes from the SQL standard, so PostgreSQL, MySQL, SQL Server and Oracle behave the same way.

The short answer

IN EXISTS
Question asked Is this value in that set? Does any matching row exist?
Works with a fixed list Yes, IN (1, 2, 3) No
Subquery style Usually independent Usually correlated
Negated form with NULLs NOT IN can return nothing NOT EXISTS is safe
Extra conditions Awkward Easy in the subquery

The sample tables

CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INT, total INT);

INSERT INTO customers VALUES (1,'Asha'), (2,'Ben'), (3,'Chitra'), (4,'Dev');
INSERT INTO orders VALUES (101,1,500), (102,1,200), (103,3,900);

Asha has two orders, Chitra has one, and Ben and Dev have none.

How IN works

SELECT name FROM customers
WHERE id IN (SELECT customer_id FROM orders);
-- Asha, Chitra

The subquery produces a list of customer IDs, here 1, 1 and 3, and each customer is kept if its ID appears in that list. IN also works with a literal list, as in WHERE status IN ('paid', 'shipped'), which is often clearer than a chain of OR conditions. Our SQL subqueries guide covers this style in more depth.

How EXISTS works

SELECT name FROM customers c
WHERE EXISTS (
  SELECT 1 FROM orders o WHERE o.customer_id = c.id
);
-- Asha, Chitra

For each customer, the subquery looks for at least one matching order. EXISTS only cares whether a row exists, not what it contains, which is why people write SELECT 1 inside. The database can stop at the first match. The subquery refers to c.id from the outer query, which makes it a correlated subquery.

Why not just use a JOIN?

SELECT c.name FROM customers c JOIN orders o ON o.customer_id = c.id;
-- Asha, Asha, Chitra

A join returns one row per match, so Asha appeared twice because of the two orders on that account. You could add DISTINCT, but that hides intent and costs extra work. When the question is “which customers have at least one order?”, IN and EXISTS express it directly and never duplicate rows. Use a join when you need columns from both tables.

The NOT IN NULL trap

Before any NULLs, NOT IN and NOT EXISTS agree:

SELECT name FROM customers WHERE id NOT IN (SELECT customer_id FROM orders);
-- Ben, Dev

SELECT name FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);
-- Ben, Dev

Now a guest order arrives with no customer:

INSERT INTO orders VALUES (104, NULL, 50);

SELECT name FROM customers WHERE id NOT IN (SELECT customer_id FROM orders);
-- (no rows)

SELECT name FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);
-- Ben, Dev

One NULL in a table of orders made NOT IN return nothing at all, while NOT EXISTS still gave the right answer. The query did not fail, so nothing alerted anyone. That is what makes this bug dangerous.

Why NULL breaks NOT IN

SQL uses three-valued logic: true, false and unknown. Comparing anything with NULL gives unknown. id NOT IN (1, 3, NULL) means “id <> 1 AND id <> 3 AND id <> NULL”. For Ben, with ID 2, the first two parts are true, but the last is unknown, so the whole condition is unknown, and WHERE only keeps rows where the condition is true. We checked the pieces directly:

SELECT 2 NOT IN (1, NULL);   -- NULL (unknown)
SELECT 1 IN (1, NULL);       -- 1 (true)
SELECT 2 IN (1, NULL);       -- NULL (unknown)

Positive IN still works when the value is found, which is why the problem only bites with NOT IN. EXISTS never returns unknown: a row either exists or it does not. Our guide to SQL NULL values explains three-valued logic in more detail.

Three safe alternatives

-- 1. NOT EXISTS (recommended)
SELECT name FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);

-- 2. Filter NULLs out of the NOT IN subquery
SELECT name FROM customers
WHERE id NOT IN (SELECT customer_id FROM orders WHERE customer_id IS NOT NULL);

-- 3. LEFT JOIN anti-join
SELECT c.name FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.id IS NULL;

All three returned Ben and Dev with the guest order present. NOT EXISTS is the most robust, because it stays correct even if someone later removes the IS NOT NULL filter or the column becomes nullable. In the LEFT JOIN version, check a column that can never be NULL in a real match, such as the primary key o.id.

Tip: Search your codebase for NOT IN (SELECT. Every match is worth a quick review: is the subquery column nullable today, or could it become nullable later? A NOT NULL constraint on foreign key columns, where the design allows it, prevents the problem at the source, as covered in primary vs foreign key.

Correlated conditions

EXISTS makes it easy to add conditions about the related rows:

SELECT name FROM customers c
WHERE EXISTS (
  SELECT 1 FROM orders o
  WHERE o.customer_id = c.id AND o.total > 400
);
-- Asha, Chitra

“Customers with at least one order over 400” reads naturally. With IN you would move the condition inside the subquery too, which works, but EXISTS scales better as conditions involve more columns from the outer table, such as matching on both customer and region.

Performance and query plans

An old rule of thumb said “EXISTS is faster than IN” or the reverse. Modern optimizers in PostgreSQL, SQL Server, Oracle and MySQL 8 usually rewrite both into the same internal operation, a semi-join for IN and EXISTS and an anti-join for NOT EXISTS, so performance is often identical. SQLite, which is simpler, showed different plans for our two queries:

IN:     SEARCH customers USING INTEGER PRIMARY KEY (rowid=?)
        LIST SUBQUERY 1
        SCAN orders
        CREATE BLOOM FILTER

EXISTS: SCAN c
        CORRELATED SCALAR SUBQUERY 1
        SCAN o

For IN, SQLite built the list of IDs once, then looked up customers by primary key. For EXISTS, it scanned customers and ran the subquery for each one. With an index on orders.customer_id, each of those lookups is fast. On tiny tables the difference is irrelevant; on large ones, read the plan for your own database and data, as described in our query optimization guide. NOT IN with nullable columns can also prevent some optimizers from using an efficient anti-join, which is another reason to prefer NOT EXISTS.

Which to use

Situation Use
Fixed list of values IN ('a', 'b')
“Has at least one related row” EXISTS or IN
“Has no related rows” NOT EXISTS
Extra conditions on related rows EXISTS
Need columns from both tables JOIN

Testing tip

Bugs like the NOT IN trap survive because test data is too clean. When testing reports and filters, always include rows with NULLs in nullable columns, rows with several matches and rows with no matches. Those three cases separate correct queries from ones that only work on tidy data. Our SQL questions for testers includes more checks like this.

Final thoughts

IN and EXISTS are interchangeable for positive checks in most databases, so choose whichever reads better. The negated forms are different: NOT IN can silently return nothing when a NULL appears, while NOT EXISTS stays correct. Make NOT EXISTS your default for “rows without a match”, and keep NULLs in your test data.

Frequently asked questions

What is the difference between EXISTS and IN in SQL?

IN checks whether a value appears in a list or subquery result. EXISTS checks whether a subquery returns at least one row. For positive checks they usually return the same rows.

Why does NOT IN return no rows?

If the subquery returns a NULL, every NOT IN comparison becomes unknown, so no rows pass the WHERE clause. In our test, one NULL order made the result empty.

Is EXISTS faster than IN?

Often there is no difference, because modern optimizers plan both as a semi-join. Check the execution plan for your own database and data.

What should I use instead of NOT IN?

Use NOT EXISTS, or filter NULLs out of the subquery, or use a LEFT JOIN with IS NULL. NOT EXISTS is the safest default.

Why use SELECT 1 inside EXISTS?

EXISTS only checks whether a row exists, so the selected columns do not matter. SELECT 1 makes that intention clear.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →