PREP WITH PROOF
Menu
SQL & DATABASES / PRACTICAL GUIDE

SQL NOT IN and NULL: Fix Unexpected Empty Results

Reproduce the SQL NOT IN NULL trap, compare NOT EXISTS and LEFT JOIN fixes, and choose explicit rules for nullable keys using tested SQL examples.

THE QUICK ANSWER

For a scalar NOT IN comparison, a NULL in a nonempty right-hand result can make an unmatched value evaluate to UNKNOWN instead of TRUE. WHERE discards that row. A correlated NOT EXISTS often expresses exclusion more clearly, but its equality predicate still needs an explicit policy for NULL keys. Choose that policy before rewriting the query.

Reproduce the missing rows with a five-row dataset

Suppose an application selects customer records that do not appear in an exclusion list. The query worked yesterday, but after a data import it returns nothing. The source records still exist, and the exclusion list contains only one known customer. The important new input may be a NULL in the exclusion list, not an optimizer change or a missing index.

The following original example uses disposable tables named candidates and blocked. Run it in an empty scratch database, not against application tables. row_id identifies an individual candidate record; customer_id is deliberately nullable. Two records refer to customer 20 so we can distinguish row identity from customer identity. The blocked row for customer 20 also has a nullable note, which will matter when examining a join rewrite.

The examples and stated result sets were executed with SQLite 3.53.1. PostgreSQL documentation supports the scalar comparison rules discussed here; this is not a claim of execution on PostgreSQL, SQL Server, or every SQL engine. Adapt schema setup and confirm behavior on your actual engine, particularly before applying the reasoning to composite keys or vendor-specific operators.

CREATE TABLE candidates (
  row_id INTEGER PRIMARY KEY,
  customer_id INTEGER
);
CREATE TABLE blocked (
  block_id INTEGER PRIMARY KEY,
  customer_id INTEGER,
  note TEXT
);
INSERT INTO candidates (row_id, customer_id)
VALUES (1, 10), (2, 20), (3, 30), (4, NULL), (5, 20);
INSERT INTO blocked (block_id, customer_id, note)
VALUES (1, 20, NULL), (2, NULL, 'Unresolved import row');

See UNKNOWN before WHERE removes the row

The unqualified exclusion condition is customer_id NOT IN (SELECT customer_id FROM blocked). With the fixture above, putting that condition in WHERE returns zero candidate records. A customer 20 comparison finds an equal value and is FALSE. Customers 10 and 30 have no equal value, but the NULL in blocked prevents the scalar NOT IN test from becoming TRUE.

Ordinary equality and inequality comparisons with NULL do not establish a known match or difference. Conceptually, 10 NOT IN (20, NULL) asks for 10 <> 20 AND 10 <> NULL. The first part is TRUE, the second UNKNOWN, and the combined result is UNKNOWN. By contrast, finding an actual equal value is enough to make the scalar NOT IN test FALSE; NULL does not turn that definite match into UNKNOWN.

Project the condition before filtering it. This CASE expression labels the outcome for every candidate so you can see the distinction between FALSE and UNKNOWN. It avoids relying on whether a database client displays a Boolean as false, 0, an empty cell, or a literal NULL. On the fixture, row IDs 1, 3, and 4 are UNKNOWN; 2 and 5 are FALSE.

SELECT c.row_id, c.customer_id,
       CASE
         WHEN c.customer_id NOT IN
              (SELECT b.customer_id FROM blocked AS b)
           THEN 'TRUE'
         WHEN NOT (c.customer_id NOT IN
              (SELECT b.customer_id FROM blocked AS b))
           THEN 'FALSE'
         ELSE 'UNKNOWN'
       END AS exclusion_result
FROM candidates AS c
ORDER BY c.row_id;

Source: PostgreSQL: EXISTS, IN, and NOT IN subquery expressions ↗

Translate the missing result into a business rule

WHERE keeps rows whose condition is TRUE. It drops both FALSE and UNKNOWN. That explains why the exclusion query can be empty even though “not listed” sounds like a yes-or-no question in ordinary language. There is no need to infer that the database lost the rows: first inspect the predicate’s result for a known missing record.

The fix depends on what an absent identifier means. An unresolved candidate may be eligible because no known exclusion matches it. Alternatively, it may need to be rejected until its identity is resolved. A third policy may deliberately treat missing identifiers as one comparable category. Those are different rules, and they can produce different correct result sets.

Write the rule as a sentence before selecting syntax. For this fixture, decide whether row 4 belongs in the output and why. A change that brings back rows 1 and 3 but silently changes the treatment of row 4 is not merely a syntax correction. Ask a domain owner to settle an unclear rule before using the query to make consequential decisions about real records.

Source: PostgreSQL: table expressions, outer joins, and WHERE ↗

Use NOT EXISTS when exclusion means no equal key exists

The correlated query below asks whether an exclusion row exists whose customer_id equals the current candidate’s customer_id. It returns candidate row IDs 1, 3, and 4. The unrelated NULL in blocked no longer prevents known nonmatching values from passing. SELECT 1 is a conventional way to express that the existence of a qualifying row is what matters.

Notice row 4. Its NULL customer_id does not equal the NULL in blocked under ordinary equality, so the inner WHERE finds no matching row. NOT EXISTS therefore includes it. This is not a magical rule that NULL has disappeared: the comparison still follows NULL semantics, while the existence test asks whether any row passed the comparison.

This form is suitable if your rule is “exclude a candidate only when an equal known key is present.” If unresolved candidates must be withheld, add c.customer_id IS NOT NULL to the outer WHERE. Keep that policy visible to future maintainers instead of relying on a side effect of a different exclusion operator.

SELECT c.row_id, c.customer_id
FROM candidates AS c
WHERE NOT EXISTS (
  SELECT 1
  FROM blocked AS b
  WHERE b.customer_id = c.customer_id
)
ORDER BY c.row_id;

Source: PostgreSQL: EXISTS, IN, and NOT IN subquery expressions ↗

If keeping NOT IN, guard both sides deliberately

Filtering NULL out of the subquery can make NOT IN suitable for comparing known identifiers. The query below also explicitly rejects candidates without an identifier. It returns row IDs 1 and 3. The two IS NOT NULL checks serve different purposes: the inner one removes unknown exclusion values; the outer one implements the policy for unknown candidates.

An inner-only filter is not the same as an unconditional rejection of outer NULL values. With this nonempty filtered right-hand result it excludes row 4, but an empty right-hand result changes that behavior. The explicit outer guard makes the rule easier to review and keeps it consistent as the contents of blocked change.

Do not replace NULL with a convenient sentinel such as -1 merely to make a comparison appear two-valued. That can make an actual -1 identifier indistinguishable from a missing one unless your schema and domain expressly rule out the collision. It can also obscure the question you need to answer: should this missing identifier be eligible, rejected, or matched to another missing identifier?

SELECT c.row_id, c.customer_id
FROM candidates AS c
WHERE c.customer_id IS NOT NULL
  AND c.customer_id NOT IN (
    SELECT b.customer_id
    FROM blocked AS b
    WHERE b.customer_id IS NOT NULL
  )
ORDER BY c.row_id;

When the rule intentionally matches NULL to NULL

If your rule deliberately treats two missing keys as a match, encode that decision in the correlation predicate. In the following scalar example, the additional OR branch matches a pair of NULL customer IDs. With the original blocked rows, the query returns row IDs 1 and 3: row 4 now finds an exclusion match.

PostgreSQL also provides IS NOT DISTINCT FROM for equality that treats two NULL inputs as matching. The explicit equality-or-both-null expression below keeps the intended policy readable without requiring that operator. This is an intentional change in meaning from the earlier ordinary-equality NOT EXISTS query.

Use this policy cautiously for identifiers. Two unknown customer identities do not necessarily identify the same person. The example demonstrates an available rule, not a recommendation that missing identities should always be grouped together. For multi-column keys, decide the meaning of each nullable component and test the whole matching condition.

SELECT c.row_id, c.customer_id
FROM candidates AS c
WHERE NOT EXISTS (
  SELECT 1
  FROM blocked AS b
  WHERE b.customer_id = c.customer_id
     OR (b.customer_id IS NULL AND c.customer_id IS NULL)
)
ORDER BY c.row_id;

Source: PostgreSQL: comparisons and IS NOT DISTINCT FROM ↗

For a LEFT JOIN rewrite, test whether a row matched

A LEFT JOIN can express the ordinary-equality anti-match too. Join on the intended comparison, then retain rows with no matched blocked record. The query below returns row IDs 1, 3, and 4, matching the ordinary-equality NOT EXISTS example. It tests b.block_id, which the fixture defines as a primary key.

Do not test b.note IS NULL to detect absence. In this fixture, customer 20 has a real matched blocked row whose note is NULL. That incorrect test would admit the excluded customer records as well. The column used to detect a missing joined row must reliably distinguish an unmatched row from a real match.

Keep the join predicate and absence test together when reviewing a change. If someone later changes the key comparison to match NULL pairs, an absence check on a nullable key can become misleading. A guaranteed non-null row identifier makes the intent explicit. Retest any additional join filters rather than assuming a rewrite preserves the earlier result.

SELECT c.row_id, c.customer_id
FROM candidates AS c
LEFT JOIN blocked AS b
  ON b.customer_id = c.customer_id
WHERE b.block_id IS NULL
ORDER BY c.row_id;

Source: PostgreSQL: table expressions, outer joins, and WHERE ↗

Include an empty exclusion list in the test matrix

The right-hand side being empty is a separate case from containing a NULL. In SQLite, scalar NOT IN against an empty subquery is TRUE even for a NULL left-hand value. The query below returns all five candidate rows. It makes the subquery empty without deleting or modifying the fixture data.

Use an empty SELECT result for the portable shape of this experiment rather than constructing NOT IN (). SQLite accepts an empty parenthesized list, but many other database engines do not. Your application’s query builder also needs an intentional rule for an empty incoming list; malformed syntax is a different failure from SQL UNKNOWN.

The comparison table summarizes the original fixture and this empty-subquery variation. It records actual row IDs from the SQLite exercise, not a performance comparison. Keep row identity in the check so that an accidental DISTINCT does not hide changed multiplicity.

Query and policyReturned row IDs
Unfiltered NOT IN with the original blocked dataNone
NOT EXISTS with ordinary equality1, 3, 4
NOT IN with explicit non-null guards on both sides1, 3
NOT EXISTS with equality or both keys NULL1, 3
LEFT JOIN with ordinary equality and block_id absence test1, 3, 4
NOT IN against the empty subquery shown here1, 2, 3, 4, 5
SELECT c.row_id, c.customer_id
FROM candidates AS c
WHERE c.customer_id NOT IN (
  SELECT b.customer_id
  FROM blocked AS b
  WHERE 1 = 0
)
ORDER BY c.row_id;

Source: SQLite: IN, NOT IN, and empty-set behavior ↗

Make the rule survive data changes

Create regression cases for an equal known key, an unmatched known key, a NULL on each side, an empty exclusion result, and duplicates. In the exercise, adding another blocked row for customer 20 should not change which candidates pass the ordinary-equality NOT EXISTS test. Adding another unmatched candidate should preserve that individual record rather than deduplicating it unexpectedly.

If the domain says a key is required, a NOT NULL constraint can enforce that requirement at the data boundary. It does not repair historical data or explain what a nullable expression inside a future query should mean. Treat schema changes as a separate migration with data validation, not an incidental quick fix during query debugging.

After correctness is established, investigate performance on representative data and your engine’s actual plan. Do not assume NOT EXISTS is universally faster than NOT IN or a join. The companion SQL plan-review article can help structure that investigation. First agree which rows belong in the output, then choose a plan that produces them efficiently.

Source: PostgreSQL: NOT NULL and primary-key constraints ↗

KEEP THESE THREE THINGS

Your next steps

  1. Inspect the exclusion predicate before WHERE so FALSE and UNKNOWN are visible.
  2. Choose an explicit policy for missing outer keys before switching to NOT EXISTS or filtering NULL.
  3. Test empty exclusion results, nullable join columns, and duplicate rows as separate cases.

Sources & official resources

Linked resources checked on 2026-10-23. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →