New: ExoBench shows the SQL your JPA mappings really send →

Postgres 19 makes NOT IN 10,000x faster, or 2,000x slower

Which one you get depends on a single NOT NULL in your schema

Summary for the Impatient

PostgreSQL 19 rewrites NOT IN into an anti join, as long as both columns are declared NOT NULL. A campaign query went from about 1.1 seconds on PG18 to 0.06 ms on PG19. Drop one NOT NULL and PG19 keeps the old plan, and it now gives up hashing the list sooner: a NOT IN over 154,199 banned customers took 44 ms on PG18 and 101.7 seconds on PG19.

Does this hit you?

  • You write NOT IN against a subquery.
  • A column on either side is declared nullable, even if it never holds a NULL. If your DDL is generated from JPA mappings, @JoinColumn defaults to nullable = true.
  • The planner expects the subquery to return between 154,199 and 262,144 rows. That's for an int key at the default work_mem.

If all three are true, that NOT IN gets slower when you upgrade to 19. If both columns are declared NOT NULL, it gets the rewrite instead.

Measured with ExoBench on Postgres 17, 18 and 19 side by side, on the 19rc2 release candidate and again on the released 19.0, which changed plans at the same rows. An AI agent that had no other way to reach a database designed the measurements.

My "contribution" to relational theory

Back in my junior days, when MSSQL 2012 or thereabouts was fresh off the presses, I had a NOT EXISTS query that took 20 seconds. I banged my head on it for a while and came up with something the guy before me hadn't thought of: LEFT JOIN the other table, and keep the rows where the joined column comes back NULL.

It worked. I had, in my own estimation, invented a groundbreaking, paradigm-shifting query optimization technique.

Turns out it's called an anti join, and thousands of people had invented it before me.

Postgres has planned NOT EXISTS as an anti join on its own since 2009. NOT IN never got one, which is why the PostgreSQL wiki's Don't Do This page tells you to stop writing it: NULLs make it return surprising results, and "the planner can't transform it into an anti-join". Then the PostgreSQL 19 release notes came out with this:

Allow NOT IN clauses to be converted to more efficient ANTI JOINs when NULLs are not present (Richard Guo)

I wanted to know what "when NULLs are not present" means in practice, and what happens to the NOT INs that don't qualify. So I gave those questions to an AI agent with ExoBench as its only way to touch a database, put Postgres 17, 18 and 19 side by side, and let it design the measurements. It ran them on the 19rc2 release candidate, and when Postgres 19.0 came out, I ran them again on the released version.

With the NOT NULL, 10,000x faster

One of its tests was a campaign preview, in the shape a jOOQ app writes it: the first 10 subscribed contacts of a tenant that haven't been emailed in the last year, against 2,000,000 generated sends. The NOT IN part:

  AND c.id NOT IN (SELECT s.contact_id
                   FROM sends s
                   WHERE s.tenant_id = 1
                     AND s.sent_at >= now() - 365 * interval '1 day')

With both columns declared NOT NULL, for tenant 1, it took about 1.1 seconds on PG18.

On PG19 it took 0.06 ms.

Benchmark SQL
benchmarkSql complete
MCP Tool✓
postgres_1825.84s computewarm ×2×10 runs
EXPLAIN (ANALYZE, BUFFERS) SELECT c.id, c.email, c.first_name
FROM contacts c
WHERE c.tenant_id = 1
  AND c.status = 'subscribed'
  AND c.id NOT IN (SELECT s.contact_id
                   FROM sends s
                   WHERE s.tenant_id = 1
                     AND s.sent_at >= now() - 365 * interval '1 day')
ORDER BY c.id
LIMIT 10
-- contact ids come in one block per tenant: tenant 1 has 20,000 contacts, tenant 2 10,000, tenant t about 12,000 / t
CREATE TABLE tenant_sizes AS SELECT t AS tenant_id, CASE WHEN t = 1 THEN 20000 WHEN t = 2 THEN 10000 ELSE greatest(5, 12000 / t) END AS n FROM generate_series(1, ${TENANTS}) t;
CREATE TABLE tenant_blocks AS SELECT tenant_id, n, (sum(n) OVER (ORDER BY tenant_id) - n + 1)::int AS first_id FROM tenant_sizes;
CREATE TABLE contacts (id INT PRIMARY KEY, tenant_id INT NOT NULL, email TEXT NOT NULL, first_name TEXT, status TEXT NOT NULL);
INSERT INTO contacts SELECT b.first_id + k, b.tenant_id, 'c' || (b.first_id + k) || '@example.com', 'Ann',
  CASE WHEN random() < 0.9 THEN 'subscribed' ELSE 'unsubscribed' END
FROM tenant_blocks b, generate_series(0, b.n - 1) k;

-- a year of sends: tenant 1 sends a third of them, tenant 2 a sixth, the rest follow a power law;
-- each tenant mails its engaged segment (every fifth contact) over and over
CREATE TABLE sends (id INT PRIMARY KEY, tenant_id INT NOT NULL, contact_id INT NOT NULL, sent_at TIMESTAMPTZ NOT NULL);
INSERT INTO sends SELECT g.i, b.tenant_id, b.first_id + 5 * floor(random() * (b.n / 5))::int, NOW() - random() * interval '365 days'
FROM (SELECT i, CASE WHEN r < 0.33 THEN 1 WHEN r < 0.495 THEN 2 ELSE 3 + floor((${TENANTS} - 2) * power(random(), 2))::int END AS t
      FROM (SELECT i, random() AS r FROM generate_series(1, ${SENDS}) i) a) g
JOIN tenant_blocks b ON b.tenant_id = g.t;
CREATE INDEX contacts_tenant_id ON contacts (tenant_id, id);
CREATE INDEX sends_tenant_sent ON sends (tenant_id, sent_at) INCLUDE (contact_id);
CREATE INDEX sends_contact ON sends (contact_id);
DROP TABLE tenant_blocks;
DROP TABLE tenant_sizes;
VACUUM ANALYZE;
ScaleTimePlanCompute
2K / 2M1.108 ±0.057 s
PG18 runs the same plan shape as PG17: a plain SubPlan over a Materialize of the 659,439 matching sends rows, stored on disk at 9,016 kB and rescanned 12 times per run on average. Mean Execution Time over 10 runs is 1,108 ms, stddev 57.16 ms.
QUERY PLAN
Statistics over 10 runs: avg = mean, stddev = sample standard deviation, omitted where 0.
Limit  (avg_cost=0.85..374566.94 avg_rows=10 avg_width=26) (actual avg_time=280.724..1106.140 stddev_time=51.887..57.159 avg_rows=10 avg_loops=1)
  Buffers: shared avg_hit=3256, temp avg_read=10148 avg_written=1127
  Disabled: false
  ->  Index Scan using contacts_tenant_id on contacts c  (avg_cost=0.85..333551105.44 avg_rows=8905 avg_width=26) (actual avg_time=275.674..1101.083 stddev_time=51.511..56.872 avg_rows=10 avg_loops=1)
        Index Cond: (tenant_id = 1)
        Filter: ((status = 'subscribed'::text) AND (NOT (ANY (id = (SubPlan 1).col1))))
        Rows Removed by Filter: avg=3
        Buffers: shared avg_hit=3256, temp avg_read=10148 avg_written=1127
        Disabled: false
        Index Searches: avg=1
        SubPlan 1
          ->  Materialize  (avg_cost=0.43..32020.13 avg_rows=657268 avg_width=4) (actual avg_time=0.006..57.908 stddev_time=0.001..3.794 avg_rows=550586.92 avg_loops=12)
                Storage: Disk  Maximum Storage: avg=9016kB
                Buffers: shared avg_hit=3252, temp avg_read=10148 avg_written=1127
                Disabled: false
                ->  Index Only Scan using sends_tenant_sent on sends s  (avg_cost=0.43..26165.79 avg_rows=657268 avg_width=4) (actual avg_time=0.031..87.993 stddev_time=0.010..13.204 avg_rows=659439 avg_loops=1)
                      Index Cond: ((tenant_id = 1) AND (sent_at >= (now() - '365 days'::interval)))
                      Heap Fetches: avg=0
                      Buffers: shared avg_hit=3252
                      Disabled: false
                      Index Searches: avg=1
Planning Time: avg=0.14 ms stddev=0.02 n=10 samples=0.16,0.11,0.13,0.12,0.12,0.15,0.15,0.11,0.16,0.19
JIT:
  Functions: avg=12
  Options: Inlining false, Optimization false, Expressions true, Deforming true
  Timing: Generation avg=0.000 ms, Inlining avg=0.000 ms, Optimization avg=0.261 ms stddev=0.050 ms, Emission avg=4.818 ms stddev=0.466 ms, Total avg=5.702 ms stddev=0.561 ms
Execution Time: avg=1108 ms stddev=57.16 n=10 samples=1245.9,1048.48,1123.52,1115.45,1063.89,1095.79,1085.38,1142.59,1055.79,1103.25
25.84s
Benchmark SQL
benchmarkSql complete
MCP Tool✓
postgres_1911.69s computewarm ×2×10 runs
EXPLAIN (ANALYZE, BUFFERS) SELECT c.id, c.email, c.first_name
FROM contacts c
WHERE c.tenant_id = 1
  AND c.status = 'subscribed'
  AND c.id NOT IN (SELECT s.contact_id
                   FROM sends s
                   WHERE s.tenant_id = 1
                     AND s.sent_at >= now() - 365 * interval '1 day')
ORDER BY c.id
LIMIT 10
-- contact ids come in one block per tenant: tenant 1 has 20,000 contacts, tenant 2 10,000, tenant t about 12,000 / t
CREATE TABLE tenant_sizes AS SELECT t AS tenant_id, CASE WHEN t = 1 THEN 20000 WHEN t = 2 THEN 10000 ELSE greatest(5, 12000 / t) END AS n FROM generate_series(1, ${TENANTS}) t;
CREATE TABLE tenant_blocks AS SELECT tenant_id, n, (sum(n) OVER (ORDER BY tenant_id) - n + 1)::int AS first_id FROM tenant_sizes;
CREATE TABLE contacts (id INT PRIMARY KEY, tenant_id INT NOT NULL, email TEXT NOT NULL, first_name TEXT, status TEXT NOT NULL);
INSERT INTO contacts SELECT b.first_id + k, b.tenant_id, 'c' || (b.first_id + k) || '@example.com', 'Ann',
  CASE WHEN random() < 0.9 THEN 'subscribed' ELSE 'unsubscribed' END
FROM tenant_blocks b, generate_series(0, b.n - 1) k;

-- a year of sends: tenant 1 sends a third of them, tenant 2 a sixth, the rest follow a power law;
-- each tenant mails its engaged segment (every fifth contact) over and over
CREATE TABLE sends (id INT PRIMARY KEY, tenant_id INT NOT NULL, contact_id INT NOT NULL, sent_at TIMESTAMPTZ NOT NULL);
INSERT INTO sends SELECT g.i, b.tenant_id, b.first_id + 5 * floor(random() * (b.n / 5))::int, NOW() - random() * interval '365 days'
FROM (SELECT i, CASE WHEN r < 0.33 THEN 1 WHEN r < 0.495 THEN 2 ELSE 3 + floor((${TENANTS} - 2) * power(random(), 2))::int END AS t
      FROM (SELECT i, random() AS r FROM generate_series(1, ${SENDS}) i) a) g
JOIN tenant_blocks b ON b.tenant_id = g.t;
CREATE INDEX contacts_tenant_id ON contacts (tenant_id, id);
CREATE INDEX sends_tenant_sent ON sends (tenant_id, sent_at) INCLUDE (contact_id);
CREATE INDEX sends_contact ON sends (contact_id);
DROP TABLE tenant_blocks;
DROP TABLE tenant_sizes;
VACUUM ANALYZE;
ScaleTimePlanCompute
2K / 2M0.06 ±0.02 ms
19rc2 rewrites the NOT IN into a Nested Loop Anti Join: it walks tenant 1's subscribed contacts in id order and probes the sends_contact index once per contact, 12 probes per run on average, until the LIMIT 10 is met. It reads 42 shared buffers per run, and the mean Execution Time over 10 runs is 0.06 ms, stddev 0.02 ms.
QUERY PLAN
Statistics over 10 runs: avg = mean, stddev = sample standard deviation, omitted where 0.
Limit  (avg_cost=0.84..9.46 avg_rows=10 avg_width=26) (actual avg_time=0.026..0.044 stddev_time=0.007..0.016 avg_rows=10 avg_loops=1)
  Buffers: shared avg_hit=42
  Disabled: false
  ->  Nested Loop Anti Join  (avg_cost=0.84..13470.56 avg_rows=15630 avg_width=26) (actual avg_time=0.026..0.043 stddev_time=0.007..0.016 avg_rows=10 avg_loops=1)
        Buffers: shared avg_hit=42
        Disabled: false
        ->  Index Scan using contacts_tenant_id on contacts c  (avg_cost=0.42..2530.02 avg_rows=18255 avg_width=26) (actual avg_time=0.017..0.020 stddev_time=0.005..0.006 avg_rows=12 avg_loops=1)
              Index Cond: (tenant_id = 1)
              Filter: (status = 'subscribed'::text)
              Rows Removed by Filter: avg=1
              Buffers: shared avg_hit=4
              Disabled: false
              Index Searches: avg=1
        ->  Index Scan using sends_contact on sends s  (avg_cost=0.43..6.67 avg_rows=42 avg_width=4) (actual avg_time=0.002..0.002 stddev_time=0.001..0.001 avg_rows=0.17 avg_loops=12)
              Index Cond: (contact_id = c.id)
              Filter: ((tenant_id = 1) AND (sent_at >= (now() - '365 days'::interval)))
              Buffers: shared avg_hit=38
              Disabled: false
              Index Searches: avg=12
Planning:
  Buffers: shared avg_hit=14
Planning Time: avg=0.2 ms stddev=0.04 n=10 samples=0.22,0.24,0.16,0.16,0.24,0.2,0.19,0.17,0.28,0.17
Execution Time: avg=0.06 ms stddev=0.02 n=10 samples=0.1,0.06,0.05,0.05,0.08,0.05,0.07,0.05,0.08,0.05
11.69s

The two plans, trimmed:

--- Postgres 18.6, avg 1,108 ms ---
Limit
  ->  Index Scan on contacts c
        Filter: ((status = 'subscribed'::text) AND (NOT (ANY (id = (SubPlan 1).col1))))
        SubPlan 1
          ->  Materialize  (... avg_loops=12)
                ->  Index Only Scan on sends s  (... avg_rows=659439)
--- Postgres 19rc2, avg 0.06 ms ---
Limit
  ->  Nested Loop Anti Join
        ->  Index Scan on contacts c
        ->  Index Scan using sends_contact on sends s  (... avg_loops=12)
              Index Cond: (contact_id = c.id)

PG18 copies the contact id of every send tenant 1 made that year into a Materialize, then runs down that copy for each contact it considers, until it has 10 that aren't on it. PG19 asks the sends_contact index about each contact, a single probe where PG18 makes a pass over the whole year.

This is really neat: the wiki's workaround, applied by the planner, to SQL behind the scenes.

Both cards are 10-run means with per-node timing on, and per-node timing slows PG18's plan down. Divided, they come to about 18,000x. With timing off, PG18 took 870.716 ms, which is still about 14,500x, so the title rounds down to 10,000x.

The released 19.0 does the same. Rechecked on Neon through ExoBench, the query averaged 0.05 ms on 19.0 and 959 ms on PG18.7, over 10 runs each.

Without it, 2,000x slower

Delete one NOT NULL, so contact_id INT NOT NULL becomes contact_id INT, and PG19 stops rewriting. Not one of the 2,000,000 sends has a NULL contact, and PG19 runs the old plan anyway, at 801.19 ms. The rewrite reads the declaration, and the data never comes into it.

That only puts the campaign query back on PG18's plan. The other test was worse, and dull on purpose: a table of orders and a growing list of banned customers.

CREATE TABLE orders (id int PRIMARY KEY, customer_id int NOT NULL, total numeric(10,2) NOT NULL);
INSERT INTO orders SELECT i, i, (i % 1000) + 0.99 FROM generate_series(1, ${O}) i;
CREATE TABLE banned (customer_id int NOT NULL);
INSERT INTO banned SELECT i * 3 FROM generate_series(1, ${B}) i;
VACUUM ANALYZE;

SELECT count(*), sum(total) FROM orders WHERE customer_id NOT IN (SELECT customer_id FROM banned);

PG17 and PG18 run a NOT IN as a filter with a SubPlan. If the planner expects the list to fit in hash memory, 8 MiB at the defaults, it hashes the list once. If it doesn't, it keeps a copy and rereads it for every order. On PG18 that line falls at exactly 262,144 ids:

--- 262,144 banned ids, 75.690 ms ---
Aggregate
  ->  Seq Scan on orders
        Filter: (NOT (ANY (customer_id = (hashed SubPlan 1).col1)))
        SubPlan 1
          ->  Seq Scan on banned
--- 262,145 banned ids, 165,878.249 ms ---
Aggregate
  ->  Seq Scan on orders
        Filter: (NOT (ANY (customer_id = (SubPlan 1).col1)))
        SubPlan 1
          ->  Materialize  (... loops=10000)
                ->  Seq Scan on banned

One more banned customer, and the query goes from 76 milliseconds to nearly three minutes. The two plans differ by the word hashed.

Now declare banned.customer_id nullable, so PG19 can't rewrite and keeps the same SubPlan. Here is PG19, one row apart:

--- PG19 154,198 banned ids, 39.764 ms ---
Aggregate
  ->  Seq Scan on orders
        Filter: (NOT (ANY (customer_id = (hashed SubPlan any_1).col1)))
        SubPlan any_1
          ->  Seq Scan on banned
--- PG19 154,199 banned ids, 101,734.255 ms 😱 ---
Aggregate
  ->  Seq Scan on orders
        Filter: (NOT (ANY (customer_id = (SubPlan any_1).col1)))
        SubPlan any_1
          ->  Materialize  (... loops=10000)
                ->  Seq Scan on banned

Take a second and count the digits in that number!

That's PG18's cliff, more than a hundred thousand ids early. At 154,199 ids PG18 still hashes the same list, in 44.066 ms:

Benchmark SQL
benchmarkSql complete
MCP Tool✓
postgres_19296.59s compute
EXPLAIN (ANALYZE, TIMING OFF, BUFFERS) SELECT count(*), sum(total) FROM orders WHERE customer_id NOT IN (SELECT customer_id FROM banned)
CREATE TABLE orders (id int PRIMARY KEY, customer_id int NOT NULL, total numeric(10,2) NOT NULL);
INSERT INTO orders SELECT i, i, (i % 1000) + 0.99 FROM generate_series(1, ${O}) i;
CREATE TABLE banned (customer_id int);
INSERT INTO banned SELECT i * 3 FROM generate_series(1, ${B}) i;
VACUUM ANALYZE;
ScaleTimePlanCompute
10K / 100K24.3 ms
At 100,000 banned ids 19rc2 leaves the NOT IN as it is, since the list column is nullable, and runs the old hashed SubPlan over one Seq Scan of banned. One execution, 24.285 ms, keeping 6,667 of the orders.
QUERY PLAN
Aggregate  (cost=1898.00..1898.01 rows=1 width=40) (actual rows=1.00 loops=1)
  Buffers: shared hit=498
  ->  Seq Scan on orders  (cost=1693.00..1873.00 rows=5000 width=6) (actual rows=6667.00 loops=1)
        Filter: (NOT (ANY (customer_id = (hashed SubPlan any_1).col1)))
        Rows Removed by Filter: 3333
        Buffers: shared hit=498
        SubPlan any_1
          ->  Seq Scan on banned  (cost=0.00..1443.00 rows=100000 width=4) (actual rows=100000.00 loops=1)
                Buffers: shared hit=443
Planning:
  Buffers: shared hit=32
Planning Time: 0.152 ms
Execution Time: 24.285 ms
0.22s
10K / 154.2K#139.8 ms
At 154,198 banned ids, the largest list 19rc2 hashes here, the Filter still reads hashed SubPlan any_1. One execution, 39.764 ms, 738 shared buffer hits.
QUERY PLAN
Aggregate  (cost=2815.48..2815.49 rows=1 width=40) (actual rows=1.00 loops=1)
  Buffers: shared hit=738
  ->  Seq Scan on orders  (cost=2610.47..2790.47 rows=5000 width=6) (actual rows=6667.00 loops=1)
        Filter: (NOT (ANY (customer_id = (hashed SubPlan any_1).col1)))
        Rows Removed by Filter: 3333
        Buffers: shared hit=738
        SubPlan any_1
          ->  Seq Scan on banned  (cost=0.00..2224.98 rows=154198 width=4) (actual rows=154198.00 loops=1)
                Buffers: shared hit=683
Planning:
  Buffers: shared hit=32
Planning Time: 0.118 ms
Execution Time: 39.764 ms
0.29s
10K / 154.2K#2101.7s
One more banned id, 154,199, and 19rc2 stops hashing: the SubPlan reads a Materialize stored on disk, rescanned 10,000 times, once per order. The one execution takes 101,734.255 ms.
QUERY PLAN
Aggregate  (cost=19922617.50..19922617.51 rows=1 width=40) (actual rows=1.00 loops=1)
  Buffers: shared hit=738, temp read=1770462 written=264
  ->  Seq Scan on orders  (cost=0.00..19922592.50 rows=5000 width=6) (actual rows=6667.00 loops=1)
        Filter: (NOT (ANY (customer_id = (SubPlan any_1).col1)))
        Rows Removed by Filter: 3333
        Buffers: shared hit=738, temp read=1770462 written=264
        SubPlan any_1
          ->  Materialize  (cost=0.00..3598.98 rows=154199 width=4) (actual rows=103360.08 loops=10000)
                Storage: Disk  Maximum Storage: 4096kB
                Buffers: shared hit=683, temp read=1770462 written=264
                ->  Seq Scan on banned  (cost=0.00..2224.99 rows=154199 width=4) (actual rows=154199.00 loops=1)
                      Buffers: shared hit=683
Planning:
  Buffers: shared hit=33
Planning Time: 0.200 ms
Execution Time: 101734.255 ms
101.71s
10K / 262.1K194.6s
At 262,144 banned ids, a list PG17 and PG18 still hash, 19rc2 runs the same plain SubPlan over a Materialize on disk, with 2,997,006 temp blocks read. One execution, 194,564.214 ms.
QUERY PLAN
Aggregate  (cost=33857805.00..33857805.01 rows=1 width=40) (actual rows=1.00 loops=1)
  Buffers: shared hit=1215, temp read=2997006 written=448
  ->  Seq Scan on orders  (cost=0.00..33857780.00 rows=5000 width=6) (actual rows=6667.00 loops=1)
        Filter: (NOT (ANY (customer_id = (SubPlan any_1).col1)))
        Rows Removed by Filter: 3333
        Buffers: shared hit=1215, temp read=2997006 written=448
        SubPlan any_1
          ->  Materialize  (cost=0.00..6116.16 rows=262144 width=4) (actual rows=175327.02 loops=10000)
                Storage: Disk  Maximum Storage: 4096kB
                Buffers: shared hit=1160, temp read=2997006 written=448
                ->  Seq Scan on banned  (cost=0.00..3781.44 rows=262144 width=4) (actual rows=262144.00 loops=1)
                      Buffers: shared hit=1160
Planning:
  Buffers: shared hit=32
Planning Time: 0.210 ms
Execution Time: 194564.214 ms
194.37s
Benchmark SQL
benchmarkSql complete
MCP Tool✓
postgres_181.40s compute
EXPLAIN (ANALYZE, TIMING OFF, BUFFERS) SELECT count(*), sum(total) FROM orders WHERE customer_id NOT IN (SELECT customer_id FROM banned)
CREATE TABLE orders (id int PRIMARY KEY, customer_id int NOT NULL, total numeric(10,2) NOT NULL);
INSERT INTO orders SELECT i, i, (i % 1000) + 0.99 FROM generate_series(1, ${O}) i;
CREATE TABLE banned (customer_id int);
INSERT INTO banned SELECT i * 3 FROM generate_series(1, ${B}) i;
VACUUM ANALYZE;
ScaleTimePlanCompute
10K / 100K36.5 ms
At 100,000 banned ids PG18 hashes the nullable list in a hashed SubPlan over one Seq Scan of banned. One execution, 36.507 ms, keeping 6,667 orders.
QUERY PLAN
Aggregate  (cost=1898.00..1898.01 rows=1 width=40) (actual rows=1.00 loops=1)
  Buffers: shared hit=498
  ->  Seq Scan on orders  (cost=1693.00..1873.00 rows=5000 width=6) (actual rows=6667.00 loops=1)
        Filter: (NOT (ANY (customer_id = (hashed SubPlan 1).col1)))
        Rows Removed by Filter: 3333
        Buffers: shared hit=498
        SubPlan 1
          ->  Seq Scan on banned  (cost=0.00..1443.00 rows=100000 width=4) (actual rows=100000.00 loops=1)
                Buffers: shared hit=443
Planning:
  Buffers: shared hit=26
Planning Time: 0.158 ms
Execution Time: 36.507 ms
0.35s
10K / 154.2K#144.1 ms
At 154,198 banned ids PG18 still hashes the list. One execution, 44.124 ms, 738 shared buffer hits.
QUERY PLAN
Aggregate  (cost=2815.48..2815.49 rows=1 width=40) (actual rows=1.00 loops=1)
  Buffers: shared hit=738
  ->  Seq Scan on orders  (cost=2610.47..2790.47 rows=5000 width=6) (actual rows=6667.00 loops=1)
        Filter: (NOT (ANY (customer_id = (hashed SubPlan 1).col1)))
        Rows Removed by Filter: 3333
        Buffers: shared hit=738
        SubPlan 1
          ->  Seq Scan on banned  (cost=0.00..2224.98 rows=154198 width=4) (actual rows=154198.00 loops=1)
                Buffers: shared hit=683
Planning:
  Buffers: shared hit=26
Planning Time: 0.108 ms
Execution Time: 44.124 ms
0.33s
10K / 154.2K#244.1 ms
At 154,199 banned ids, where 19rc2 stops hashing this same list, PG18 keeps the hashed SubPlan. One execution, 44.066 ms, for the same 6,667 orders.
QUERY PLAN
Aggregate  (cost=2815.49..2815.50 rows=1 width=40) (actual rows=1.00 loops=1)
  Buffers: shared hit=738
  ->  Seq Scan on orders  (cost=2610.49..2790.49 rows=5000 width=6) (actual rows=6667.00 loops=1)
        Filter: (NOT (ANY (customer_id = (hashed SubPlan 1).col1)))
        Rows Removed by Filter: 3333
        Buffers: shared hit=738
        SubPlan 1
          ->  Seq Scan on banned  (cost=0.00..2224.99 rows=154199 width=4) (actual rows=154199.00 loops=1)
                Buffers: shared hit=683
Planning:
  Buffers: shared hit=26
Planning Time: 0.152 ms
Execution Time: 44.066 ms
0.29s
10K / 262.1K79.5 ms
At 262,144 banned ids, the largest list PG18 hashes, the hashed SubPlan reads 1,215 shared buffers. One execution, 79.451 ms.
QUERY PLAN
Aggregate  (cost=4641.80..4641.81 rows=1 width=40) (actual rows=1.00 loops=1)
  Buffers: shared hit=1215
  ->  Seq Scan on orders  (cost=4436.80..4616.80 rows=5000 width=6) (actual rows=6667.00 loops=1)
        Filter: (NOT (ANY (customer_id = (hashed SubPlan 1).col1)))
        Rows Removed by Filter: 3333
        Buffers: shared hit=1215
        SubPlan 1
          ->  Seq Scan on banned  (cost=0.00..3781.44 rows=262144 width=4) (actual rows=262144.00 loops=1)
                Buffers: shared hit=1160
Planning:
  Buffers: shared hit=26
Planning Time: 0.139 ms
Execution Time: 79.451 ms
0.42s

Same NOT IN, same data, same answer, about 2,300 times slower on PG19 than on PG18 and about 2,000 times slower than on PG17. Here's the whole sweep:

NOT IN execution time as the banned list grows, 10,000 orders, one execution per point with EXPLAIN (ANALYZE, TIMING OFF, BUFFERS): PostgreSQL 17.11, 18.6 and 19rc2 with banned.customer_id declared without NOT NULL, and 19rc2 with both columns NOT NULL.
Both panels are linear and share one x-axis drawn to scale: runs that reread the list above, in seconds, and runs that hash the list or anti-join below, in milliseconds. A dotted line is a jump from one panel to the other.
0 s100 s200 s300 s0 ms25 ms50 ms75 ms100 ms100,000154,199262,145500,000Banned ids in the NOT IN list, to scale (10,000 orders)Rereads the list for every order (seconds)Hashes the list, or anti-joins (milliseconds)+1 id: 40 ms → 102 sPG19 nullable 345 sPG17 nullable 315 sPG18 nullable 309 sPG19 NOT NULL 47 ms
With a nullable list, 19rc2 jumps to the seconds panel at 154,199 banned ids while PG17 and PG18 keep hashing through 262,144, and 19rc2's anti join on NOT NULL columns never leaves the milliseconds panel.
Execution time per point, one execution each, 10,000 orders. PG17, nullable list: 28.683 ms at 100,000 banned ids, 52.754 ms at 154,198, 51.777 ms at 154,199 and 80.391 ms at 262,144 on the hashed SubPlan, then 165,261.775 ms at 262,145 and 314,769.094 ms at 500,000 on the plain SubPlan. PG18, nullable list: 36.507 ms, 44.124 ms, 44.066 ms and 79.451 ms hashed at those four sizes, then 162,743.662 ms at 262,145 and 309,423.976 ms at 500,000 on the plain SubPlan. PG19, nullable list: 24.285 ms at 100,000 and 39.764 ms at 154,198 hashed, then 101,734.255 ms at 154,199, 194,564.214 ms at 262,144, 182,753.052 ms at 262,145 and 345,100.858 ms at 500,000 on the plain SubPlan. PG19, both columns NOT NULL, a Hash Right Anti Join at every size: 10.729 ms, 15.605 ms, 16.598 ms, 27.021 ms, 25.135 ms and 46.841 ms.
Chart data measured with ExoBench

From 154,199 banned ids to 262,144, a NOT IN that PG19 won't rewrite rereads the list for every order, and PG17 and PG18 still hash it.

The released 19.0 draws the line at the same row. On Neon, through ExoBench, it took 68 seconds over 154,199 banned ids, rereading the list for every order, where PG18.7 hashed the same list in 31 ms.

The cliff moved because of a separate PG19 commit, Tom Lane's "Improve planner's estimates of tuple hash table sizes" (1ea5bdb00bf). PG19's estimate now counts the hash table's bucket array and, for a NOT IN, a second table for NULLs, and for 154,199 ints it comes out ten bytes over the 8 MiB limit. The check is pass or fail, so ten bytes over gets the plan that rereads the list. The release notes list the NOT IN rewrite and say nothing about this commit.

The agent walked into it

I didn't go looking for the gap. On Nov 12, on 19rc1, the agent ran the 90-day version of the campaign query with contact_id nullable and got 248.15 ms, where PG18 hashed the same list in 43.83 ms.

There's very little about this online. In the ban-list session the agent searched the web, found Tom Lane's commit, and worked out from the code that PG19 would stop hashing an int NOT IN at about 154,199 rows. Less than two minutes after its last search, its first ExoBench call put the list one row either side of that number, and the cliff was right there.

How this was measured

The experimenter was the stock OpenHands agent running Claude Opus 5.5, sealed in a Docker container. Inside it had a shell, web search and a local ExoBench 1.4.26 as an MCP server, and no database ports, so ExoBench was its only way to a database. ExoBench ran each call against three Docker servers, postgres:17 (17.11), postgres:18 (18.6) and postgres:19rc2, at default settings, and returned every plan with its timings. A separate gateway logged every call verbatim, and every card on this page is cut from that log.

Over four agent sessions and one I scripted myself, that came to 266 ExoBench calls, 4 h 50 min of agent time and $40 of model cost.

PostgreSQL 19.0 came out after those sessions. On Dec 1 I reran the key tests on it myself, without the agent, through ExoBench on Neon, with 19.0 next to PG17 and PG18 and the same hash memory. That took 19 more calls, and every plan changed at the same row as on the release candidates.

Just a few caveats to stay honest:

  • The cards are 19rc2. 19rc1 drew the same plans wherever it ran the same test, and so did the released 19.0.
  • One laptop, default settings, int keys. The plan shapes and the rows where they change carry over to any 64-bit machine at the same settings. 19.0 on Neon's ARM servers changed plans at the same rows. The milliseconds don't carry over: the slow plan at 154,199 ids took 68 seconds there and 102 on the laptop. Other key widths and memory settings move both cliffs.
  • Mostly single runs on the ban list, because the slow ones take minutes. The differences here are a thousandfold.

Every result was correct on all three versions, for the int columns, built-in = and uncast subqueries that were tested. The full write-up has all of it: 38 cards, the hash-size arithmetic to the byte, the rewrite rules from the source and the correctness checks, in Postgres 19 makes NOT IN 10,000x faster... or 2,000x slower.

The fix, in the order I'd try it

  1. Declare the columns NOT NULL if they never hold a NULL. With JPA-generated DDL, that's nullable = false on the @JoinColumn.
  2. If the schema can't promise that for the subquery's column, add WHERE col IS NOT NULL inside the subquery. PG19 accepts that as proof on the subquery's side. The same filter on the outer column doesn't count.
  3. Or write NOT EXISTS, which Postgres has planned as an anti join since PostgreSQL 8.4, in 2009.

If none of those is possible, look at the planner's row estimate for the subquery in EXPLAIN. For an int at the default work_mem, an estimate between 154,199 and 262,144 is a NOT IN that gets slower when you upgrade.

Postgres finally invents the anti join for you, as long as you promise it there are no NULLs. Make the promise in the schema.

About the author

Alexander Ioffe

I've hand-tuned thousands of SQL queries in financial services, most of them a page or longer, and I don't recommend it. So I built ExoBench, where an AI assistant proposes a fix and a real database has to prove it.

More about me →

New posts by RSS