December 5, 2026

SQL NULL and Three-Valued Logic: Why NOT IN Returned Nothing and Other Surprises

A clipboard form with one box ticked yes, one no and one left empty

A query asks for every row whose value is not in a list of banned values. The table has three rows; one is banned. The query returns zero rows. Nothing is wrong with the database. The banned list contains a NULL, and in SQL a comparison with NULL is neither true nor false but unknown, and a WHERE clause keeps only rows where the condition is true. Running a set of small NULL tests through SQLite 3.53.1 and DuckDB 2.0.1 shows where this third truth value hides, which surprises both engines share, and where they quietly disagree.

Video: The SQL Professor on YouTube

NULL means unknown, not empty

The basic rule

PostgreSQL’s documentation states the rule plainly: “Do not write expression = NULL because NULL is not “equal to” NULL. (The null value represents an unknown value, and it is not known whether two unknown values are equal.)” PostgreSQL documentation, Comparison Functions and Operators

Both engines agreed. SELECT null = null, null <> null, null IS NULL returned NULL, NULL and true. Asking whether two unknowns are equal gives an unknown answer; asking whether something is unknown gives a real yes. Only IS NULL and IS NOT NULL answer the question that = NULL appears to ask.

Three truth values

Logic with NULL follows a consistent table. The tests returned:

Expression Result
NULL AND FALSE FALSE
NULL AND TRUE NULL
NULL OR TRUE TRUE
NULL OR FALSE NULL
NOT NULL NULL

The pattern is that NULL acts like a value that could be either true or false. NULL AND FALSE is false no matter what the unknown turns out to be, so the answer is definite. NULL AND TRUE depends on the unknown, so it stays unknown. SQLite printed false as 0 and true as 1; DuckDB printed True and False; the logic was identical.

Industrial shelving units with various items stored

The test table

Three rows, one missing value

The tests used a table t with ids 1, 2 and 3 and values 1, 2 and NULL, plus a table banned holding the values 2 and NULL.

WHERE drops unknowns

SELECT id FROM t WHERE v <> 1 returned only id 2. Row 3, with a NULL value, was not returned, even though NULL is certainly not the number 1 in everyday terms. The comparison NULL <> 1 evaluated to unknown, and WHERE treats unknown the same as false.

That is the single most common NULL bug: a filter written to exclude one value also silently excludes every row where the column is empty.

The NOT IN trap

Zero rows

SELECT id FROM t WHERE v NOT IN (SELECT v FROM banned) returned an empty result in both SQLite and DuckDB. The intended answer was id 1, the only row whose value is not 2.

PostgreSQL’s subquery documentation explains why: “if there are no equal right-hand values and at least one right-hand row yields null, the result of the NOT IN construct will be null, not true.” PostgreSQL documentation, Subquery Expressions For id 1, 1 NOT IN (2, NULL) means 1 <> 2 AND 1 <> NULL, which is TRUE AND NULL, which is NULL. The row is dropped. The same documentation adds that a NULL on the left also makes the result null, which removed row 3. Every row lost.

IN is not affected the same way

WHERE v IN (SELECT v FROM banned) returned id 2 as expected. IN only needs one match to become true, and a NULL in the list cannot stop a real match from counting.

NOT EXISTS behaves differently

Rewriting the query with NOT EXISTS (SELECT 1 FROM banned b WHERE b.v = t.v) returned ids 1 and 3 in both engines. NOT EXISTS asks whether any matching row exists, and an unknown comparison simply does not count as a match. Row 3 came back because nothing in banned was provably equal to its NULL. Whether row 3 should be in the answer is a business decision, but at least the query does not collapse to nothing.

Wooden card catalog drawers with labels

Comparisons that treat NULL as a value

IS DISTINCT FROM

Sometimes NULL should be compared like an ordinary value. PostgreSQL’s documentation describes IS DISTINCT FROM as “the same as the <> operator” for non-null inputs, but “if both inputs are null it returns false, and if only one input is null it returns true.” The predicates “effectively act as though null were a normal data value, rather than “unknown”.”

SELECT id FROM t WHERE v IS DISTINCT FROM 1 returned ids 2 and 3 in both SQLite and DuckDB, the answer the <> query was probably meant to give.

COALESCE

coalesce(v, 0) replaced the NULL with 0, returning 1, 2 and 0. That is the right tool when a missing value genuinely means zero, such as an unbilled amount, and the wrong one when it means “not measured,” where turning it into zero changes averages and totals.

Strings

'a' || NULL returned NULL in both engines. Joining any text to an unknown gives an unknown; a report that builds a full name from first, middle and last name columns loses the whole name when the middle name is NULL, unless each part is wrapped in coalesce.

Joins on NULL keys

Joins follow the same rule. A table a with keys 1, NULL and NULL was joined to a table b with keys 1 and NULL. An ordinary JOIN ... ON a.k = b.k produced one row in both engines: only the 1s matched, and neither NULL key matched the NULL in b. Rewriting the condition as a.k IS NOT DISTINCT FROM b.k produced three rows, the 1 plus each of the two NULL keys paired with the NULL label row. And SELECT DISTINCT k FROM a returned two values, 1 and NULL, collapsing the two NULLs into one, the inconsistency SQLite’s page describes.

Aggregates, sorting and constraints

Aggregates skip NULLs

SELECT count(*), count(v), sum(v), avg(v) FROM t returned 3, 2, 3 and 1.5. The row with the missing value counted as a row but not as a value, and the average was 3 divided by 2, not by 3. That matches how aggregates are designed, but it means avg() over a column with gaps averages only the known values.

Sorting: the engines disagree

Ordering by v gave different results. SQLite returned NULL, 1, 2. DuckDB returned 1, 2, NULL.

Both engines are following their own documentation. SQLite’s says it “considers NULL values to be smaller than any other values for sorting purposes,” so NULLs “naturally appear at the beginning of an ASC order-by and at the end of a DESC order-by.” SQLite documentation, SELECT DuckDB’s says: “By default, DuckDB sorts ASC and NULLS LAST,” and offers a default_null_order setting to change it. DuckDB documentation, ORDER BY Sorted descending, both put NULL last.

A query that relies on where NULLs land will change behavior when moved between engines. Writing ORDER BY v ASC NULLS LAST or NULLS FIRST explicitly removes the ambiguity in both.

UNIQUE allows several NULLs

Inserting NULL twice into a column declared UNIQUE succeeded in both engines, leaving two rows. SQLite’s page on NULL handling records the same rule: “NULLs are still distinct in a UNIQUE column.” The same page admits that NULLs are treated as indistinct for SELECT DISTINCT and UNION, and calls the combination “puzzling,” saying “It seems that NULLs should be either distinct everywhere or nowhere.” SQLite, NULL Handling in SQLite Versus Other Database Engines

CHECK constraints pass unknowns

A table with CHECK (age >= 0) rejected -1 in both engines but accepted NULL. A CHECK constraint fails only when its condition is false; NULL >= 0 is unknown, so the row is allowed. A column that must always hold a valid value needs NOT NULL alongside its CHECK.

Laptop computer on glass-top table

Writing NULL-safe SQL

CASE needs three branches

A CASE expression with WHEN v = 1 THEN 'one' WHEN NOT (v = 1) THEN 'not one' ELSE 'unknown' sorted the three rows into all three branches: ‘one’, ‘not one’ and ‘unknown’. Code that assumes every row lands in one of two branches will send NULL rows to the ELSE, or to NULL if there is no ELSE.

A checklist

  • Use IS NULL and IS NOT NULL, never = NULL.
  • Prefer NOT EXISTS to NOT IN with a subquery, or filter NULLs out of the subquery.
  • Use IS DISTINCT FROM when NULL should compare as an ordinary value.
  • Decide what a missing value means before using coalesce.
  • Add NOT NULL to columns that must have values, and do not rely on CHECK alone.
  • State NULLS FIRST or NULLS LAST in any ORDER BY whose output order matters.

Why it stays this way

SQLite’s NULL page describes testing several popular engines and finding a “wide variety of behaviors” that has since “converged toward the PostgreSQL/Oracle model.” Three-valued logic is not going away; it is the agreed meaning of an unknown value, and the safest SQL is the kind that says out loud what an unknown should do.

Sources

  • PostgreSQL documentation, 9.2. Comparison Functions and Operators: https://www.postgresql.org/docs/current/functions-comparison.html
  • PostgreSQL documentation, 9.25. Subquery Expressions: https://www.postgresql.org/docs/current/functions-subquery.html
  • SQLite documentation, SELECT (ORDER BY): https://www.sqlite.org/lang_select.html
  • SQLite, NULL Handling in SQLite Versus Other Database Engines: https://www.sqlite.org/nulls.html
  • DuckDB documentation (2.0), ORDER BY Clause: https://duckdb.org/docs/2.0/sql/query_syntax/orderby.html

920 Posts

Peter Kalafatis writes and edits X9M8. He holds a bachelor's degree from LIU Post and a master's in Media Studies from The New School, with academic work in the philosophy of science, human behavior, AI, and memetics.

View All Posts

Leave a Reply

Your email address will not be published. Required fields are marked *