Database engineer reviewing PostgreSQL composite NOT IN query results for tenant keys containing NULL values.

Why Composite NOT IN Hides Some PostgreSQL Rows

Wed, Nov 25, 2026

Two candidate keys can look almost interchangeable in a tenant-scoped absence review and still produce different results under PostgreSQL row-valued NOT IN. If candidate (7,10) is compared with reference (7,NULL), the pair is not provably unequal: the tenant fields match and the external-ID comparison is unknown. If the reference is (8,NULL), the unequal tenant component is enough to make the row comparison unequal. PostgreSQL documents exactly this distinction for row constructors: corresponding non-null unequal members make two rows unequal; otherwise a null-bearing comparison can remain unknown. Row-valued NOT IN is true only when every reference row is unequal, including the special case of an empty subquery.

That Boolean behavior is only half of a defensible absence report. In this playbook, tenant_id is known and non-null, while a null external_id means unresolved identity, not a real business-key category. A query can therefore return SQL TRUE while the reporting policy still requires HOLD_IDENTITY.

The protocol below fixes twelve independent cases, evaluates three predicates, preserves TRUE, FALSE, and UNKNOWN before filtering, reconciles exact case identities, verifies unchanged source fixtures, and separates SQL evidence from owner decisions. The intended environment is PostgreSQL 18.7, released November 12, 2026, with psql 18.7 and server_version_num = 180007; the comparison rules themselves are PostgreSQL 18 behavior, not something introduced by that patch.

Everything labeled EXPECTED / NOT EXECUTED is a manually authored prediction for this article. No PostgreSQL session was run for this brief, so no transcript, digest, process status, approval, or observed result is invented.

Define the absence decision before changing SQL

An absence report needs a data contract before it needs a rewrite. For this qualification, a candidate identity consists of a non-null integer tenant_id plus a nullable integer external_id. The reference export is reviewed within the same named batch, tenant scope, and observation boundary. Query results cannot establish whether that export was complete: source coverage is an external fact that the source owner must attest.

That distinction matters because SQL absence queries and data grain can answer whether rows satisfy a predicate, but this review asks something narrower: whether each included identity is justified as absent when part of the key may be unresolved. The predicate result and the reporting decision therefore occupy separate ledgers.

The primary contract for this batch is deliberately conservative:

  • a complete matching identity is KEEP_MATCH;

  • a candidate whose own external_id is null is HOLD_IDENTITY;

  • a complete candidate that encounters a same-tenant reference with null external_id is also HOLD_IDENTITY, unless a complete match already proves the candidate is present;

  • a complete candidate with no complete match and no unresolved same-tenant reference can be ACCEPT_ABSENCE, but only when source coverage has been attested;

  • malformed, incomplete, or owner-correctable source identity is REPAIR_INPUT; missing qualification evidence is RERUN_EVIDENCE.

Those decisions are owner policy, not PostgreSQL truth values.

Give NULL one meaning for this batch

Here, NULL external_id means “identity not resolved.” It does not mean a real external-ID category, “all external IDs,” “tenant default,” or a sentinel value. PostgreSQL ordinary comparisons involving null generally yield null/unknown, while IS NOT DISTINCT FROM deliberately supplies different null-aware semantics by treating two null operands as not distinct.

That documented flexibility is precisely why the owner must specify the meaning first. A database reviewer can prove what ROW(...) NOT IN (...), ordinary NOT EXISTS, and null-safe NOT EXISTS do. The reviewer cannot infer from SQL alone whether two missing external IDs should represent the same business identity.

Source ownership is therefore explicit. The source owner attests the batch boundary, reference coverage, and meaning of missing IDs. The database reviewer checks the predicates and evidence. The report owner decides whether the included and excluded populations satisfy the reporting contract.

Pin the environment and comparison syntax

The reproducibility target is PostgreSQL 18.7 with psql 18.7 and server numeric version 180007. PostgreSQL’s 18.7 release notes give a release date of November 12, 2026 and describe the patch as fixes relative to 18.6; they do not make these row-comparison semantics an 18.7 invention.

A real qualification should preserve the actual psql --version output, server version(), server_version_num, database, role, script digest, complete transcript, and shell process status. PostgreSQL documents psql --version; -X suppresses system and user psqlrc startup files; -f executes a file and provides useful script line-number reporting; and ON_ERROR_STOP=on terminates noninteractive script processing when an error is encountered.

psql exit status is useful evidence but not a semantic oracle. PostgreSQL documents status 0 for normal completion, 1 for a fatal psql error, 2 for a lost server connection in a noninteractive session, and 3 for a script error when ON_ERROR_STOP is set. A status of 0 says execution completed normally; it does not prove that the authored expected truth table or business policy was correct.

Use a fresh disposable database or equivalent lab target and a fresh session. Temporary tables are session-local and are automatically dropped at session end. PostgreSQL creates them in a special temporary schema, so the script should create names unqualified and subsequently reference them explicitly through pg_temp.

Keep row constructors separate from composite datums

The surface under review is:

ROW(c.tenant_id, c.external_id) NOT IN (
    SELECT r.tenant_id, r.external_id
    FROM pg_temp.reference_rows AS r
    WHERE r.case_id = c.case_id
)

The subquery returns exactly two columns because PostgreSQL requires a row-constructor IN/NOT IN subquery to return the same number of columns as the left-hand row.

Do not replace this with a single named composite datum or SELECT ROW(r.*). PostgreSQL documents row-constructor comparison separately from comparison of composite-type datums, and their null treatment in other comparison contexts should not be conflated.

This article also excludes row lexicographic ordering. Only equality-style membership matters. Nor should reasoning depend on procedural left-to-right Boolean execution: PostgreSQL’s three-valued logical operators define outcomes, while the documentation explicitly warns that operand evaluation order is not guaranteed.

Freeze twelve independent cases and their oracle

The test population contains twelve candidate rows and thirteen reference rows. Each case is isolated by case_id, so every reference subquery must include r.case_id = c.case_id. N12 intentionally contains two source identities, R1 and R2, carrying the same key value; the duplicate remains present so the protocol can demonstrate that duplicate membership rows do not alter the Boolean result.

Case

Candidate key

Reference keys for this case only

A

B

C

Policy

N01

(7,10)

empty

T

T

T

ACCEPT_ABSENCE

N02

(7,10)

(7,10)

F

F

F

KEEP_MATCH

N03

(7,10)

(7,11)

T

T

T

ACCEPT_ABSENCE

N04

(7,10)

(7,NULL)

U

T

T

HOLD_IDENTITY

N05

(7,10)

(8,NULL)

T

T

T

ACCEPT_ABSENCE

N06

(7,NULL)

(7,10)

U

T

T

HOLD_IDENTITY

N07

(7,NULL)

(8,10)

T

T

T

HOLD_IDENTITY

N08

(7,NULL)

(7,NULL)

U

T

F

HOLD_IDENTITY

N09

(7,NULL)

empty

T

T

T

HOLD_IDENTITY

N10

(7,10)

(7,10); (7,NULL)

F

F

F

KEEP_MATCH

N11

(7,10)

(7,11); (7,NULL)

U

T

T

HOLD_IDENTITY

N12

(7,10)

(7,NULL); (7,NULL)

U

T

T

HOLD_IDENTITY

Oracle status: EXPECTED / NOT EXECUTED. It contains 12 candidate identities, 13 reference-source identities, 36 case/predicate truth cells, and 12 policy classifications. The values are authored expectations derived from the documented contracts, not captured PostgreSQL output. Row-valued NOT IN is predicted using PostgreSQL’s rules for exact equality, definite inequality, unknown row comparison, exact-match dominance, and an empty right-hand subquery.

Freeze expectations before evaluating predicates

The expected fixture, truth cells, selected sets, and policy decisions should be literal data written before the predicates are evaluated. Do not generate the oracle by rerunning the expression under test; that would compare an implementation with itself rather than with an independent expectation.

The following wrapper records the client version and actual digest without inventing either value. The SQL file below is the qualification script; save it as qualify_composite_not_in.sql. PostgreSQL documents -X, -f, --version, ON_ERROR_STOP, and process statuses as used here.

#!/usr/bin/env bash
set -u

SQL_FILE=qualify_composite_not_in.sql
TRANSCRIPT=qualify_composite_not_in.transcript.txt

psql --version
sha256sum "$SQL_FILE"

set +e
psql -X \
  -v ON_ERROR_STOP=1 \
  -f "$SQL_FILE" \
  >"$TRANSCRIPT" 2>&1
status=$?
set -e

printf 'psql_exit_status=%s\n' "$status"
printf 'transcript=%s\n' "$TRANSCRIPT"

exit "$status"

The complete SQL is below. It creates temporary names without IF NOT EXISTS, so an unexpected collision fails rather than silently reusing unknown state. Temporary objects are then referenced through pg_temp. PostgreSQL documents that temporary tables live in a special temporary schema and are session-scoped.

\set ON_ERROR_STOP on
\pset pager off
\echo 'STATUS: EXPECTED / NOT EXECUTED in article; this file is runnable evidence code'

SELECT
    version() AS server_version,
    current_setting('server_version_num') AS server_version_num,
    current_database() AS database_name,
    current_user AS role_name;

DO $$
BEGIN
    IF current_setting('server_version_num')::integer <> 180007 THEN
        RAISE EXCEPTION
            'wrong server_version_num: expected 180007, got %',
            current_setting('server_version_num');
    END IF;
END
$$;

BEGIN;

CREATE TEMP TABLE candidates (
    case_id     text PRIMARY KEY,
    tenant_id   integer NOT NULL,
    external_id integer
) ON COMMIT PRESERVE ROWS;

CREATE TEMP TABLE reference_rows (
    case_id     text NOT NULL REFERENCES candidates(case_id),
    source_id   text NOT NULL,
    tenant_id   integer NOT NULL,
    external_id integer,
    PRIMARY KEY (case_id, source_id)
) ON COMMIT PRESERVE ROWS;

INSERT INTO pg_temp.candidates(case_id, tenant_id, external_id) VALUES
('N01',7,10),
('N02',7,10),
('N03',7,10),
('N04',7,10),
('N05',7,10),
('N06',7,NULL),
('N07',7,NULL),
('N08',7,NULL),
('N09',7,NULL),
('N10',7,10),
('N11',7,10),
('N12',7,10);

INSERT INTO pg_temp.reference_rows
    (case_id, source_id, tenant_id, external_id)
VALUES
('N02','R1',7,10),
('N03','R1',7,11),
('N04','R1',7,NULL),
('N05','R1',8,NULL),
('N06','R1',7,10),
('N07','R1',8,10),
('N08','R1',7,NULL),
('N10','R1',7,10),
('N10','R2',7,NULL),
('N11','R1',7,11),
('N11','R2',7,NULL),
('N12','R1',7,NULL),
('N12','R2',7,NULL);

-- Independent literal fixture manifests.
CREATE TEMP TABLE expected_candidates (
    case_id text PRIMARY KEY,
    tenant_id integer NOT NULL,
    external_id integer
) ON COMMIT PRESERVE ROWS;

INSERT INTO pg_temp.expected_candidates VALUES
('N01',7,10),('N02',7,10),('N03',7,10),('N04',7,10),
('N05',7,10),('N06',7,NULL),('N07',7,NULL),('N08',7,NULL),
('N09',7,NULL),('N10',7,10),('N11',7,10),('N12',7,10);

CREATE TEMP TABLE expected_references (
    case_id text NOT NULL,
    source_id text NOT NULL,
    tenant_id integer NOT NULL,
    external_id integer,
    PRIMARY KEY(case_id,source_id)
) ON COMMIT PRESERVE ROWS;

INSERT INTO pg_temp.expected_references VALUES
('N02','R1',7,10),
('N03','R1',7,11),
('N04','R1',7,NULL),
('N05','R1',8,NULL),
('N06','R1',7,10),
('N07','R1',8,10),
('N08','R1',7,NULL),
('N10','R1',7,10),
('N10','R2',7,NULL),
('N11','R1',7,11),
('N11','R2',7,NULL),
('N12','R1',7,NULL),
('N12','R2',7,NULL);

CREATE TEMP TABLE expected_truth (
    case_id text NOT NULL,
    branch text NOT NULL CHECK (branch IN ('A','B','C')),
    expected_value boolean,
    PRIMARY KEY(case_id,branch)
) ON COMMIT PRESERVE ROWS;

INSERT INTO pg_temp.expected_truth VALUES
('N01','A',TRUE), ('N01','B',TRUE), ('N01','C',TRUE),
('N02','A',FALSE),('N02','B',FALSE),('N02','C',FALSE),
('N03','A',TRUE), ('N03','B',TRUE), ('N03','C',TRUE),
('N04','A',NULL), ('N04','B',TRUE), ('N04','C',TRUE),
('N05','A',TRUE), ('N05','B',TRUE), ('N05','C',TRUE),
('N06','A',NULL), ('N06','B',TRUE), ('N06','C',TRUE),
('N07','A',TRUE), ('N07','B',TRUE), ('N07','C',TRUE),
('N08','A',NULL), ('N08','B',TRUE), ('N08','C',FALSE),
('N09','A',TRUE), ('N09','B',TRUE), ('N09','C',TRUE),
('N10','A',FALSE),('N10','B',FALSE),('N10','C',FALSE),
('N11','A',NULL), ('N11','B',TRUE), ('N11','C',TRUE),
('N12','A',NULL), ('N12','B',TRUE), ('N12','C',TRUE);

CREATE TEMP TABLE expected_policy (
    case_id text PRIMARY KEY,
    expected_decision text NOT NULL
) ON COMMIT PRESERVE ROWS;

INSERT INTO pg_temp.expected_policy VALUES
('N01','ACCEPT_ABSENCE'),
('N02','KEEP_MATCH'),
('N03','ACCEPT_ABSENCE'),
('N04','HOLD_IDENTITY'),
('N05','ACCEPT_ABSENCE'),
('N06','HOLD_IDENTITY'),
('N07','HOLD_IDENTITY'),
('N08','HOLD_IDENTITY'),
('N09','HOLD_IDENTITY'),
('N10','KEEP_MATCH'),
('N11','HOLD_IDENTITY'),
('N12','HOLD_IDENTITY');

CREATE TEMP TABLE expected_selected (
    branch text NOT NULL,
    case_id text NOT NULL,
    PRIMARY KEY(branch,case_id)
) ON COMMIT PRESERVE ROWS;

INSERT INTO pg_temp.expected_selected VALUES
('A','N01'),('A','N03'),('A','N05'),('A','N07'),('A','N09'),
('B','N01'),('B','N03'),('B','N04'),('B','N05'),('B','N06'),
('B','N07'),('B','N08'),('B','N09'),('B','N11'),('B','N12'),
('C','N01'),('C','N03'),('C','N04'),('C','N05'),('C','N06'),
('C','N07'),('C','N09'),('C','N11'),('C','N12');

-- Evaluate predicates without filtering away UNKNOWN.
CREATE TEMP TABLE truth_ledger (
    case_id text NOT NULL,
    branch text NOT NULL,
    predicate_value boolean,
    PRIMARY KEY(case_id,branch)
) ON COMMIT PRESERVE ROWS;

INSERT INTO pg_temp.truth_ledger
SELECT c.case_id, 'A',
       ROW(c.tenant_id,c.external_id) NOT IN (
           SELECT r.tenant_id,r.external_id
           FROM pg_temp.reference_rows AS r
           WHERE r.case_id = c.case_id
       )
FROM pg_temp.candidates AS c
UNION ALL
SELECT c.case_id, 'B',
       NOT EXISTS (
           SELECT 1
           FROM pg_temp.reference_rows AS r
           WHERE r.case_id = c.case_id
             AND r.tenant_id = c.tenant_id
             AND r.external_id = c.external_id
       )
FROM pg_temp.candidates AS c
UNION ALL
SELECT c.case_id, 'C',
       NOT EXISTS (
           SELECT 1
           FROM pg_temp.reference_rows AS r
           WHERE r.case_id = c.case_id
             AND r.tenant_id IS NOT DISTINCT FROM c.tenant_id
             AND r.external_id IS NOT DISTINCT FROM c.external_id
       )
FROM pg_temp.candidates AS c;

-- Diagnostic projection: preserve three-valued evidence.
SELECT case_id,
       branch,
       predicate_value,
       CASE
           WHEN predicate_value IS TRUE THEN 'TRUE'
           WHEN predicate_value IS FALSE THEN 'FALSE'
           WHEN predicate_value IS UNKNOWN THEN 'UNKNOWN'
           ELSE 'IMPOSSIBLE'
       END AS truth_label
FROM pg_temp.truth_ledger
ORDER BY case_id, branch;

-- Owner policy is evaluated separately from A/B/C.
CREATE TEMP TABLE policy_ledger (
    case_id text PRIMARY KEY,
    decision text NOT NULL
) ON COMMIT PRESERVE ROWS;

INSERT INTO pg_temp.policy_ledger
SELECT c.case_id,
       CASE
           WHEN c.external_id IS NULL
               THEN 'HOLD_IDENTITY'
           WHEN EXISTS (
               SELECT 1
               FROM pg_temp.reference_rows AS r
               WHERE r.case_id = c.case_id
                 AND r.tenant_id = c.tenant_id
                 AND r.external_id = c.external_id
                 AND r.external_id IS NOT NULL
           )
               THEN 'KEEP_MATCH'
           WHEN EXISTS (
               SELECT 1
               FROM pg_temp.reference_rows AS r
               WHERE r.case_id = c.case_id
                 AND r.tenant_id = c.tenant_id
                 AND r.external_id IS NULL
           )
               THEN 'HOLD_IDENTITY'
           ELSE 'ACCEPT_ABSENCE'
       END
FROM pg_temp.candidates AS c;

SELECT 
FROM pg_temp.policy_ledger
ORDER BY case_id;

-- Exact truth comparison; NULL is compared as a value for evidence purposes.
CREATE TEMP TABLE truth_discrepancy AS
SELECT e.case_id,
       e.branch,
       e.expected_value,
       a.predicate_value AS actual_value
FROM pg_temp.expected_truth AS e
FULL JOIN pg_temp.truth_ledger AS a
  USING (case_id,branch)
WHERE e.case_id IS NULL
   OR a.case_id IS NULL
   OR e.expected_value IS DISTINCT FROM a.predicate_value;

-- Exact selected identity sets, in both directions.
CREATE TEMP TABLE selected_discrepancy AS
WITH actual_selected AS (
    SELECT branch,case_id
    FROM pg_temp.truth_ledger
    WHERE predicate_value IS TRUE
),
missing AS (
    SELECT branch,case_id
    FROM pg_temp.expected_selected
    EXCEPT
    SELECT branch,case_id
    FROM actual_selected
),
extra AS (
    SELECT branch,case_id
    FROM actual_selected
    EXCEPT
    SELECT branch,case_id
    FROM pg_temp.expected_selected
)
SELECT 'MISSING'::text AS problem, branch, case_id FROM missing
UNION ALL
SELECT 'EXTRA', branch, case_id FROM extra;

CREATE TEMP TABLE policy_discrepancy AS
SELECT e.case_id,
       e.expected_decision,
       a.decision AS actual_decision
FROM pg_temp.expected_policy AS e
FULL JOIN pg_temp.policy_ledger AS a USING (case_id)
WHERE e.case_id IS NULL
   OR a.case_id IS NULL
   OR e.expected_decision IS DISTINCT FROM a.decision;

-- Detect fixture mutation, including NULL substitutions and source IDs.
CREATE TEMP TABLE input_discrepancy AS
SELECT 'candidate_missing_or_changed'::text AS problem,
       e.case_id,
       NULL::text AS source_id
FROM pg_temp.expected_candidates AS e
LEFT JOIN pg_temp.candidates AS a USING (case_id)
WHERE a.case_id IS NULL
   OR e.tenant_id IS DISTINCT FROM a.tenant_id
   OR e.external_id IS DISTINCT FROM a.external_id
UNION ALL
SELECT 'candidate_extra', a.case_id, NULL
FROM pg_temp.candidates AS a
LEFT JOIN pg_temp.expected_candidates AS e USING (case_id)
WHERE e.case_id IS NULL
UNION ALL
SELECT 'reference_missing_or_changed', e.case_id, e.source_id
FROM pg_temp.expected_references AS e
LEFT JOIN pg_temp.reference_rows AS a USING (case_id,source_id)
WHERE a.case_id IS NULL
   OR e.tenant_id IS DISTINCT FROM a.tenant_id
   OR e.external_id IS DISTINCT FROM a.external_id
UNION ALL
SELECT 'reference_extra', a.case_id, a.source_id
FROM pg_temp.reference_rows AS a
LEFT JOIN pg_temp.expected_references AS e
  USING (case_id,source_id)
WHERE e.case_id IS NULL;

-- Completeness and uniqueness checks.
DO $$
BEGIN
    IF (SELECT count() FROM pg_temp.candidates) <> 12 THEN
        RAISE EXCEPTION 'candidate count mismatch';
    END IF;
    IF (SELECT count(*) FROM pg_temp.reference_rows) <> 13 THEN
        RAISE EXCEPTION 'reference count mismatch';
    END IF;
    IF (SELECT count(*) FROM pg_temp.truth_ledger) <> 36 THEN
        RAISE EXCEPTION 'truth ledger must contain exactly 36 identities';
    END IF;
    IF (SELECT count(*) FROM pg_temp.policy_ledger) <> 12 THEN
        RAISE EXCEPTION 'policy ledger must contain exactly 12 identities';
    END IF;
    IF EXISTS (SELECT 1 FROM pg_temp.truth_discrepancy) THEN
        RAISE EXCEPTION 'truth discrepancy found';
    END IF;
    IF EXISTS (SELECT 1 FROM pg_temp.selected_discrepancy) THEN
        RAISE EXCEPTION 'selected identity discrepancy found';
    END IF;
    IF EXISTS (SELECT 1 FROM pg_temp.policy_discrepancy) THEN
        RAISE EXCEPTION 'policy discrepancy found';
    END IF;
    IF EXISTS (SELECT 1 FROM pg_temp.input_discrepancy) THEN
        RAISE EXCEPTION 'fixture mutation or substitution found';
    END IF;
END
$$;

-- Preserve complete ordered evidence in the transcript.
SELECT FROM pg_temp.candidates ORDER BY case_id;
SELECT FROM pg_temp.reference_rows ORDER BY case_id,source_id;
SELECT FROM pg_temp.expected_truth ORDER BY case_id,branch;
SELECT FROM pg_temp.truth_ledger ORDER BY case_id,branch;
SELECT FROM pg_temp.expected_selected ORDER BY branch,case_id;
SELECT FROM pg_temp.policy_ledger ORDER BY case_id;

SELECT FROM pg_temp.truth_discrepancy ORDER BY case_id,branch;
SELECT FROM pg_temp.selected_discrepancy ORDER BY branch,case_id,problem;
SELECT FROM pg_temp.policy_discrepancy ORDER BY case_id;
SELECT FROM pg_temp.input_discrepancy ORDER BY problem,case_id,source_id;

ROLLBACK;

No output from that script is claimed here. Its assertions define what a future captured run would need to satisfy.

Project the three predicates before filtering

Branch A is the exact PostgreSQL composite NOT IN question. Branch B asks whether no reference row makes two ordinary equality predicates true. Branch C asks whether no reference row matches under explicit null-safe equivalence.

PostgreSQL documents EXISTS as true when its subquery returns at least one row and false when it returns none. Ordinary = yields unknown when either operand is null. IS NOT DISTINCT FROM instead returns true for two null inputs and false when exactly one side is null.

The three branches are therefore deliberately different:

-- A: row-valued NOT IN
ROW(c.tenant_id, c.external_id) NOT IN (
    SELECT r.tenant_id, r.external_id
    FROM pg_temp.reference_rows AS r
    WHERE r.case_id = c.case_id
)

-- B: ordinary-equality anti-membership
NOT EXISTS (
    SELECT 1
    FROM pg_temp.reference_rows AS r
    WHERE r.case_id = c.case_id
      AND r.tenant_id = c.tenant_id
      AND r.external_id = c.external_id
)

-- C: explicit null-safe anti-membership
NOT EXISTS (
    SELECT 1
    FROM pg_temp.reference_rows AS r
    WHERE r.case_id = c.case_id
      AND r.tenant_id IS NOT DISTINCT FROM c.tenant_id
      AND r.external_id IS NOT DISTINCT FROM c.external_id
)

The point is not to declare one universally superior. The point is to make each question visible and compare its exact population with the approved data contract. That evidence discipline is related to Refonte Learning’s treatment of three-valued predicate audits, but the present qualification is specifically about two-column anti-membership and unresolved identity.

Preserve UNKNOWN before WHERE removes it

The diagnostic ledger must materialize the nullable Boolean value before using it as a row-selection condition. PostgreSQL allows explicit classification with IS TRUE, IS FALSE, and IS UNKNOWN.

That is why the runnable script stores predicate_value boolean and labels it afterward:

CASE
    WHEN predicate_value IS TRUE THEN 'TRUE'
    WHEN predicate_value IS FALSE THEN 'FALSE'
    WHEN predicate_value IS UNKNOWN THEN 'UNKNOWN'
END

Do not write:

CASE WHEN predicate_value THEN 'TRUE' ELSE 'FALSE' END

because that collapses both FALSE and UNKNOWN into the same diagnostic label.

This matters operationally because a WHERE condition retains rows for which its condition is true and discards rows for which it is false or null. A production-looking SELECT ... WHERE row_key NOT IN (...) can therefore hide the distinction between “definitely not selected” and “selection predicate unknown.” PostgreSQL’s table-expression documentation states that only rows satisfying the WHERE condition are retained.

Compare a same-tenant NULL with a definite mismatch

N04 and N05 are the most useful control pair in the fixture.

For N04, candidate (7,10) meets reference (7,NULL). The first corresponding fields are equal. The second comparison, 10 = NULL, is unknown under ordinary comparison semantics. PostgreSQL’s row-comparison rule says two row constructors are equal only when all corresponding members are non-null and equal; they are unequal when at least one corresponding pair is non-null and unequal; otherwise equality is unknown. No field establishes definite inequality here, so the pair comparison remains unknown.

With no equal row and at least one unknown comparison, row-valued NOT IN is therefore predicted UNKNOWN for N04. PostgreSQL’s subquery documentation describes NOT IN as true when only unequal rows are found, false when an equal row is found, and null when neither condition can be established because null-bearing comparisons remain unresolved.

For N05, candidate (7,10) meets (8,NULL). The tenant pair 7 versus 8 is definitively unequal. PostgreSQL’s row equality rule says one corresponding non-null unequal pair is sufficient to make the row pair unequal. The unresolved external-ID component cannot undo that definite mismatch. N05 is therefore predicted TRUE under A.

N03, (7,10) against (7,11), is the complete-key control: equal tenant, definitely unequal external ID, therefore an unequal row and TRUE for NOT IN.

These are truth rules, not claims about a particular evaluation sequence. SQL’s logical operators use three-valued logic, but PostgreSQL does not promise that the left operand of a Boolean expression is procedurally evaluated before the right.

The useful correction to a common simplification is narrow: a null anywhere on the right side of a multicolumn NOT IN does not automatically suppress every unmatched candidate. The result depends on the row comparisons that remain after considering definite inequalities and exact matches.

Test nullable candidates against empty and different-tenant references

N06, N07, and N09 show why a nullable candidate needs its own policy even when PostgreSQL can sometimes produce an unambiguous Boolean result.

N06 compares (7,NULL) with (7,10). The tenant fields are equal, while the external-ID equality is unknown. There is no definitely unequal component, so row equality is unknown and A is predicted UNKNOWN.

N07 compares (7,NULL) with (8,10). The non-null tenant fields differ, making the pair unequal regardless of the unresolved external ID. A is therefore predicted TRUE. N09 has no reference rows at all. PostgreSQL explicitly documents an empty right-hand subquery as a TRUE case for NOT IN, because only unequal rows have been found vacuously.

Yet both N07 and N09 remain HOLD_IDENTITY under this article’s policy. That is not a disagreement with PostgreSQL. It is a separate business statement: the candidate itself lacks the external ID required to make an absence claim about a complete identity.

The empty-set case requires another operational boundary. An owner-attested empty reference set can legitimately participate in the qualification. An export that is empty because extraction failed, a tenant was omitted, credentials expired, or the observation boundary was incomplete cannot authorize an absence result merely because SQL sees zero rows. Source completeness must be evidenced outside the anti-membership predicate.

Show what exact matches and duplicate references change

N10 and N11 demonstrate exact-match dominance.

N10 compares candidate (7,10) with two references: (7,10) and (7,NULL). One reference row is exactly equal. PostgreSQL documents row-valued NOT IN as false if any equal row is found; the additional unknown-producing row does not convert that false result to unknown. N10 is therefore predicted FALSE under A.

That outcome also aligns with the business decision: the complete identity is known to exist, so KEEP_MATCH is justified even though another same-tenant reference is unresolved.

N11 contains (7,11) and (7,NULL) for candidate (7,10). The first reference is definitely unequal; the second is unknown. There is no equal reference, but the comparisons are not all definitely unequal. A is therefore predicted UNKNOWN.

N12 repeats (7,NULL) under distinct source identities R1 and R2. Both pair comparisons remain unknown, so repeating the same value does not make the membership answer more certain: A remains UNKNOWN, B remains TRUE, and C remains TRUE.

The fixture deliberately preserves both source IDs. Duplicate source-value provenance is evidence even when it does not alter membership truth. This article does not turn that observation into an UPDATE ... FROM cardinality discussion or deduplicate the input before demonstrating the control.

Interpret what ordinary NOT EXISTS actually proves

Branch B is:

NOT EXISTS (
    SELECT 1
    FROM pg_temp.reference_rows AS r
    WHERE r.case_id = c.case_id
      AND r.tenant_id = c.tenant_id
      AND r.external_id = c.external_id
)

PostgreSQL defines EXISTS in terms of whether the subquery returns any row. The two ordinary equality predicates inside that subquery must therefore become true for a row to count as a match.

When either side of r.external_id = c.external_id is null, ordinary equality is unknown rather than true. Because a WHERE clause does not retain a row whose condition is null, such a reference does not produce an EXISTS match.

That explains N04. (7,NULL) does not satisfy r.external_id = 10, so no true equality match exists; B returns TRUE. N06 similarly fails to find a true equality match between 10 and the candidate’s null external ID. In N08, even NULL versus NULL does not make ordinary = true; B again returns TRUE. These are expected consequences of the question B asks.

Branch B is not defective. It simply proves a narrower proposition: no reference row exists for which both ordinary equality predicates are true. It does not prove that every unresolved reference identity is irrelevant to the report owner.

Its authored selected set is:

Branch

EXPECTED / NOT EXECUTED selected identities

Count

A

N01, N03, N05, N07, N09

5

B

N01, N03, N04, N05, N06, N07, N08, N09, N11, N12

10

C

N01, N03, N04, N05, N06, N07, N09, N11, N12

9

The ten B identities are therefore not a recommendation for the final report. They are the exact fixture population selected by B under the authored expectations.

This is the central review distinction: changing NOT IN to ordinary-equality NOT EXISTS changes the logical question for nullable key components. A rewrite is acceptable only when the new question is the one the data contract actually intends.

Evaluate null-safe matching as a policy choice

Branch C replaces ordinary equality with IS NOT DISTINCT FROM. PostgreSQL documents that predicate as equivalent to equality for non-null values, true when both inputs are null, and false when only one input is null.

The visible difference is N08. Candidate (7,NULL) and reference (7,NULL) are a match under C because both tenant IDs are not distinct and both external IDs are not distinct. EXISTS is therefore true and NOT EXISTS false. Under B, the null external-ID equality never became true, so B returned true instead.

C’s authored selected identities are:

N01, N03, N04, N05, N06, N07, N09, N11, N12.

That is nine rows, with N08 removed from B’s ten-row set.

There are valid contracts where null-safe matching is exactly what an owner wants. For example, if a missing key component has been explicitly approved as a genuine category and two nulls are intended to denote the same identity, IS NOT DISTINCT FROM can encode that equality policy directly. PostgreSQL provides the predicate specifically for null-aware comparison.

But that is not the primary contract here. This batch defines null as unresolved identity. Treating two unresolved external IDs as the same completed identity would silently change the business semantics.

That distinction mirrors why nullable uniqueness and business identity must be specified separately from ordinary SQL equality: different database surfaces can deliberately use different null-equivalence rules. The cited Refonte playbook concerns constraint enforcement, whereas this one remains a read-time anti-membership qualification.

If an owner adopts a new null-as-category policy, do not merely swap predicates and keep the old approval. Author a new oracle, classify all cases under that policy, identify the affected reports, and review the new population.

Apply the owner-approved absence policy

The reporting decision can now be implemented independently from A, B, and C. The required order is important because a complete candidate match should preserve the known record before unresolved same-tenant references are considered.

CASE
    WHEN c.external_id IS NULL
        THEN 'HOLD_IDENTITY'

    WHEN EXISTS (
        SELECT 1
        FROM pg_temp.reference_rows AS r
        WHERE r.case_id = c.case_id
          AND r.tenant_id = c.tenant_id
          AND r.external_id = c.external_id
          AND r.external_id IS NOT NULL
    )
        THEN 'KEEP_MATCH'

    WHEN EXISTS (
        SELECT 1
        FROM pg_temp.reference_rows AS r
        WHERE r.case_id = c.case_id
          AND r.tenant_id = c.tenant_id
          AND r.external_id IS NULL
    )
        THEN 'HOLD_IDENTITY'

    ELSE 'ACCEPT_ABSENCE'
END

The EXPECTED / NOT EXECUTED decision populations are:

Decision

Exact identities

Meaning in this fixture

ACCEPT_ABSENCE

N01, N03, N05

Complete candidate; no complete match; no unresolved same-tenant reference

KEEP_MATCH

N02, N10

A complete matching reference exists

HOLD_IDENTITY

N04, N06, N07, N08, N09, N11, N12

Candidate or relevant reference identity is unresolved

ACCEPT_ABSENCE remains conditional on verified batch completeness. N01’s empty reference is useful only if “empty” is itself an owner-attested source fact. N03 has a same-tenant but definitely different complete key. N05 has an unresolved reference under a different tenant, and the known tenant mismatch makes it irrelevant to this tenant’s identity under the stated contract.

N10 shows why ordering the policy matters. It has both (7,10) and (7,NULL) on the reference side. The complete match is sufficient to preserve the known identity, so KEEP_MATCH wins. The unresolved sibling reference still belongs in evidence, but it cannot manufacture an absence.

Unknown tenant IDs are outside this protocol because tenant_id is declared NOT NULL in both fixture inputs.

Do not manufacture absence by filtering missing keys

A tempting rewrite is to remove all reference rows where external_id IS NULL before testing absence. That does not “fix” NOT IN; it changes the source population by discarding unresolved evidence. N04 and N11 would then look cleaner only because the information blocking an absence claim had been removed.

Coalescing null to an arbitrary sentinel has the same problem. A value such as -1 is a real integer in SQL unless the surrounding contract forbids and assigns special meaning to it. Substitution converts “unknown identity” into an invented identity category and alters equality behavior.

Neither operation is an authorized input repair in this protocol. Missing identifiers stay visible and are routed to the source owner. The review must not turn incomplete source knowledge into a positive absence claim merely to obtain two-valued SQL output.

Reconcile truth, selected IDs, and unchanged inputs

A qualification should fail on substituted identities even when row counts happen to match. The script therefore expects exactly 36 unique (case_id, branch) truth identities and 12 unique policy identities, then compares each nullable Boolean with its literal expected value using IS DISTINCT FROM.

That null-safe evidence comparison is appropriate because the question at that point is not the business key’s equality semantics. It is whether an observed nullable Boolean cell is exactly the authored expected cell, including whether it is null. PostgreSQL documents IS DISTINCT FROM/IS NOT DISTINCT FROM for precisely such comparisons where null must be treated as an explicit comparison state.

The same review discipline applies to row identity. Refonte Learning’s article on row-identity reconciliation in PostgreSQL updates focuses on a different write scenario, but its provenance lesson is relevant here: counts alone do not prove that the intended identities are present.

For this fixture, exact truth partitions are:

Branch

TRUE identities

FALSE identities

UNKNOWN identities

A

N01, N03, N05, N07, N09

N02, N10

N04, N06, N08, N11, N12

B

N01, N03, N04, N05, N06, N07, N08, N09, N11, N12

N02, N10

none

C

N01, N03, N04, N05, N06, N07, N09, N11, N12

N02, N08, N10

none

All entries remain EXPECTED / NOT EXECUTED.

Reject missing, extra, or substituted evidence

The acceptance procedure should establish all of the following, not merely a total row count:

  1. The candidate fixture contains exactly the literal twelve (case_id, tenant_id, external_id) rows.

  2. The reference fixture contains exactly thirteen (case_id, source_id, tenant_id, external_id) rows, preserving N12’s R1 and R2.

  3. The truth ledger contains one and only one row for every expected (case_id, branch) pair.

  4. Each actual nullable Boolean is compared against its literal expected value with IS DISTINCT FROM.

  5. Selected populations are reconciled in both directions: expected-minus-actual detects missing identities; actual-minus-expected detects extras.

  6. Policy identities are likewise compared by case, not merely counted.

  7. Candidate and reference fixtures are compared again at the end so a missing, extra, changed, or null-substituted value is detectable.

The complete A selected population must be exactly {N01,N03,N05,N07,N09}. Its unknown population must be exactly {N04,N06,N08,N11,N12} and its false population exactly {N02,N10}.

B must select exactly {N01,N03,N04,N05,N06,N07,N08,N09,N11,N12}. C must select exactly {N01,N03,N04,N05,N06,N07,N09,N11,N12}.

The owner policy must independently produce ACCEPT_ABSENCE={N01,N03,N05}, KEEP_MATCH={N02,N10}, and HOLD_IDENTITY={N04,N06,N07,N08,N09,N11,N12}.

An empty discrepancy table is meaningful only after those completeness and uniqueness checks have established what was compared. A test that accidentally produced 35 truth cells could otherwise report “no mismatching values” simply because the missing identity never reached the comparison.

For a real run, retain the complete ordered candidate and reference manifests, expected oracle, observed truth ledger, selected-set reconciliation, policy ledger, version capture, script digest, transcript, and process status as one evidence package. Keep expected fields explicitly separate from observed fields. A normal psql exit status is one artifact in that package, not a replacement for semantic reconciliation.

Repair unresolved inputs and revalidate the report

REPAIR_INPUT does not mean editing the fixture until the expected matrix passes. Candidate and reference inputs remain unchanged after setup. The qualification is intended to describe what the reviewed batch actually contained.

If an unresolved external ID can be corrected, the source owner should provide the owner-approved identifier through the source’s normal correction process. Preserve the original batch and its evidence, identify the corrected input as a new batch, and rerun the entire qualification against that new reviewed population. If the owner instead changes the meaning of null (for example, explicitly making null a real identity category), that is a policy revision and likewise needs a new oracle and review.

Do not invent a replacement ID, filter the unresolved reference out, or coalesce it to make the selected set match a preferred answer.

If an incorrect absence report has already been issued, database-session cleanup is not downstream remediation. PostgreSQL documents ROLLBACK as discarding updates made by the current transaction. That database guarantee says nothing about retracting a CSV, dashboard extract, message, file, API payload, or report already published outside the transaction.

The reporting process should therefore preserve provenance, withdraw or mark the affected report invalid under its established controls, regenerate it from corrected reviewed inputs, and reconcile the downstream consumers that received the incorrect population. No destructive production SQL is needed for this playbook.

The final ROLLBACK in the disposable script only discards the current transaction’s lab changes. Temporary tables would also be removed at session end under PostgreSQL’s documented temporary-table lifecycle.

Make the release decision and assign ownership

The final review is not “which anti-join syntax do we prefer?” It is whether the evidence proves the approved absence population for the named batch.

Decision

Required condition

Owner / next action

ACCEPT_ABSENCE

Approved unresolved-identity policy; source coverage attested; reviewed inputs unchanged; complete observed qualification matches oracle; exact report population reconciles

Report owner may approve only the justified absence identities

KEEP_MATCH

Complete candidate/reference identity is known to match

Preserve the identity from the absence population

HOLD_IDENTITY

Candidate identity is incomplete, or a relevant same-tenant reference remains unresolved

Block absence classification pending owner resolution

REPAIR_INPUT

Source identity is wrong/incomplete, or the owner explicitly revises null meaning

Source/data owner produces a newly reviewed batch or policy

RERUN_EVIDENCE

Wrong PostgreSQL/psql version, missing transcript/digest/status, incomplete run, failed assertion, or incomplete artifacts

Database reviewer reruns the qualification from frozen inputs

This kind of evidence gate can later be incorporated into automating database change checks, but automation does not replace the owner-defined semantics or the independent expected manifest.

Ownership should remain separated. The source owner attests batch completeness, tenant coverage, observation boundary, and the meaning of missing external IDs. The database reviewer checks the PostgreSQL predicates, independent oracle, environment, unchanged inputs, and exact reconciliation. The report owner approves which identities are included or excluded under the reporting contract.

Reopen the review whenever the key columns change, tenant nullability changes, source scope changes, null/equality policy changes, or the query shape changes. A source-only article such as this one, containing documented mechanics and EXPECTED / NOT EXECUTED predictions, supports a qualification protocol proposal. It does not constitute an observed release pass.

The practical release rule is therefore stricter than “the query returned the five expected A rows.” Under the approved policy, only three cases (N01, N03, and N05) qualify for the absence report, and even those require independently verified reference completeness. That conclusion is bounded to the authored twelve-case fixture and declared policy; it does not prove every rewrite, every data distribution, every production snapshot, or every future batch.

Continue developing database review skills with Refonte Learning

The habits exercised here (reasoning about SQL semantics, defining identity contracts, reconciling exact populations, preserving evidence, and assigning owner decisions) sit naturally alongside broader database-administration skills.

Refonte Learning’s Database Administrator Essentials program page lists a three-month program at 12–14 hours per week. It names competencies including database design, SQL query optimization, backup and recovery, performance tuning, security, migration and integration, and monitoring; its learning path also includes Advanced SQL Techniques. The page lists basic programming knowledge as recommended and separately states that applicants must be working toward a bachelor’s or higher-level degree.

The page describes a “Potential Internship”, not guaranteed placement, and says successful completion leads to a Training Certificate and Certificate of Internship.