Catch SQL NOT IN failures with a NULL fixture

Use a minimal SQLite fixture and an exact-result assertion to catch exclusion queries that break when a subquery contains NULL.

OpenThunder Editorial · 2026-11-25

Imagine a refactor that replaces NOT EXISTS with NOT IN: with candidate IDs 1, 2, and 3, excluding 2 works with either query. Add NULL to the exclusions, and NOT IN returns [] instead of the expected [1, 3].

Both queries execute successfully. An assertion on the returned IDs catches this regression even when execution succeeds.

Define what a NULL exclusion row means

The contract for this fixture is:

Input or rule Value
Candidate IDs 1, 2, 3, all non-null and unique
Exclusion IDs 2, NULL
Meaning of a null exclusion ID It matches no candidate
Expected output Exactly 1, 3

The meaning of a null exclusion ID is a business decision, not something SQL can infer. If it should instead invalidate the input, test for rejection rather than silently ignoring it.

Why NOT IN returns no rows

Consider this query against the fixture above:

SELECT c.id
FROM candidates AS c
WHERE c.id NOT IN (
    SELECT e.id
    FROM exclusions AS e
)
ORDER BY c.id;

For candidate 1, the predicate behaves like:

1 <> 2 AND 1 <> NULL

The first comparison is true. The second is unknown, because an ordinary comparison with NULL does not produce true or false. True combined with unknown through AND remains unknown.

A WHERE clause keeps only rows whose predicate is true:

Candidate NOT IN (2, NULL) result Kept?
1 Unknown No
2 False No
3 Unknown No

The query succeeds syntactically and returns an empty result. A check that only verifies successful execution will miss the defect.

Put the query behind an isolated regression test

Use the application's existing query path when available, so the test exercises the SQL that can actually change in production. If the application constructs SQL dynamically, execute that generated SQL in the test; if it loads a query file, use its query-loading path. Otherwise, production code can change while an unused SQL file continues to pass.

A passing test protects only the code path it executes.

For a standalone demonstration, use two files: a query file and a test that reads it, rather than embedding a second copy of the query. This layout uses Python's standard-library sqlite3 and unittest modules and an in-memory database, with no external database service.

Create queries/exclude_candidates.sql:

SELECT c.id
FROM candidates AS c
WHERE NOT EXISTS (
    SELECT 1
    FROM exclusions AS e
    WHERE e.id = c.id
)
ORDER BY c.id;

The correlated subquery asks whether an equal exclusion ID exists for each candidate. An exclusion row containing NULL does not satisfy e.id = c.id. Candidate 2 has a match and is removed; candidates 1 and 3 have no match and remain.

Create tests/test_exclusion.py:

from pathlib import Path
import sqlite3
import unittest


QUERY_PATH = (
    Path(__file__).resolve().parents[1]
    / "queries"
    / "exclude_candidates.sql"
)


class ExclusionContractTest(unittest.TestCase):
    def test_null_exclusion_preserves_unmatched_candidates(self):
        db = sqlite3.connect(":memory:")
        self.addCleanup(db.close)

        db.executescript("""
            CREATE TABLE candidates (
                id INTEGER NOT NULL UNIQUE
            );

            CREATE TABLE exclusions (
                id INTEGER
            );

            INSERT INTO candidates (id) VALUES (1), (2), (3);
            INSERT INTO exclusions (id) VALUES (2), (NULL);
        """)

        query = QUERY_PATH.read_text(encoding="utf-8")
        actual = [row[0] for row in db.execute(query).fetchall()]

        self.assertEqual(
            [1, 3],
            actual,
            "A NULL exclusion must not remove unmatched candidates",
        )


if __name__ == "__main__":
    unittest.main()

The exact list assertion catches missing rows, extra rows, and duplicate output. The query includes ORDER BY so the comparison does not depend on unspecified row order.

Run the assertion in CI

Run this command from the repository root in a CI job with Python and its SQLite module available:

python -m unittest discover -s tests -p 'test_*.py'

A failed assertion produces a nonzero exit status. Configure the job as a required check if it should block merging.

Static analysis can complement this check by flagging a nullable subquery or enforcing a query policy. The executable fixture answers a different question: does this query return the rows the contract requires?

Exclusion-query checklist

Use these four signals when reviewing an exclusion-query change:

Signal Required check
Exclusion IDs can contain NULL Include both a matching ID and NULL in one fixture.
Candidate IDs can contain NULL Define their treatment separately. With a null candidate and exclusions containing 2, ordinary-equality NOT EXISTS retains that candidate while filtered NOT IN drops it. This fixture assumes non-null candidates.
Query construction changed Verify that the test executes the changed query path.
Production uses another database engine Run the contract against that engine as well.

For non-null candidate IDs, filtering nulls out of the subquery is another possible implementation:

WHERE c.id NOT IN (
    SELECT e.id
    FROM exclusions AS e
    WHERE e.id IS NOT NULL
)

I would choose correlated NOT EXISTS for these semantics because it directly expresses the contract: retain a candidate when no equal exclusion ID exists. If performance matters, measure it on the deployed engine with representative data and inspect the query plan.

With ordinary equality, no comparison matches a null candidate, which explains the distinction in the checklist. Do not generalize the equivalence beyond the tested contract.

Verify that the assertion rejects the refactor

In five minutes, create the two files and run the unittest command above. After it passes, temporarily replace the query file with the unfiltered NOT IN version and rerun it.

The deliberate change should fail with actual output [] instead of [1, 3]. That failure checks that the assertion distinguishes the implementations, rather than merely exercising the database. Restore NOT EXISTS before committing, and keep the corrected query and fixture together in version control.

This SQLite demonstration does not establish behavior under your deployed engine's SQL dialect or schema constraints.