BUG #17545: Incorrect selectivity for IS NOT DISTINCT FROM and NULLs
BUG #17545: Incorrect selectivity for IS NOT DISTINCT FROM and NULLs
От:
PG Bug reporting form <noreply@postgresql.org>
Дата:
The following bug has been logged on the website:
Bug reference: 17545
Logged by: Roope Salmi
Email address: rpsalmi@gmail.com
PostgreSQL version: 14.4
Operating system: Ubuntu 22.04
Description:
Hi,
It appears that selectivity for "IS NOT DISTINCT FROM" clauses regard the
proportion of NULLs in the same way as "=", leading to polar opposite row
count
estimates.
In practice this causes nested loop joins to be used when that is not
appropriate. Not sure if this is a known issue, but I was unable to find
any
previous mentions of it.
Here I create a table with one column and 1000 rows of NULL. A cartesian
product
with "WHERE x.a = y.a" correctly estimates that there are around zero
matching
rows. "x.a IS NOT DISTINCT FROM y.a" incorrectly gives the same estimate,
whereas "x.a = y.a OR (x.a IS NULL AND y.a IS NULL)", which should be
equivalent, gives the correct 1000000.
postgres=# CREATE TABLE test(a INTEGER);
CREATE TABLE
postgres=# INSERT INTO test(a) SELECT NULL FROM generate_series(1, 1000);
INSERT 0 1000
postgres=# ANALYZE test;
ANALYZE
postgres=# EXPLAIN SELECT FROM test x, test y WHERE x.a = y.a;
QUERY PLAN
----------------------------------------------------------------------
Merge Join (cost=127.66..137.67 rows=1 width=0)
Merge Cond: (x.a = y.a)
-> Sort (cost=63.83..66.33 rows=1000 width=4)
Sort Key: x.a
-> Seq Scan on test x (cost=0.00..14.00 rows=1000 width=4)
-> Sort (cost=63.83..66.33 rows=1000 width=4)
Sort Key: y.a
-> Seq Scan on test y (cost=0.00..14.00 rows=1000 width=4)
(8 rows)
postgres=# EXPLAIN SELECT FROM test x, test y
postgres=# WHERE x.a IS NOT DISTINCT FROM y.a;
QUERY PLAN
----------------------------------------------------------------------
Nested Loop (cost=0.00..15030.50 rows=1 width=0)
Join Filter: (NOT (x.a IS DISTINCT FROM y.a))
-> Seq Scan on test x (cost=0.00..14.00 rows=1000 width=4)
-> Materialize (cost=0.00..19.00 rows=1000 width=4)
-> Seq Scan on test y (cost=0.00..14.00 rows=1000 width=4)
(5 rows)
postgres=# EXPLAIN SELECT FROM test x, test y
postgres-# WHERE x.a = y.a OR (x.a IS NULL AND y.a IS NULL);
QUERY PLAN
----------------------------------------------------------------------
Nested Loop (cost=0.00..15030.50 rows=1000000 width=0)
Join Filter: ((x.a = y.a) OR ((x.a IS NULL) AND (y.a IS NULL)))
-> Seq Scan on test x (cost=0.00..14.00 rows=1000 width=4)
-> Materialize (cost=0.00..19.00 rows=1000 width=4)
-> Seq Scan on test y (cost=0.00..14.00 rows=1000 width=4)
(5 rows)
Re: BUG #17545: Incorrect selectivity for IS NOT DISTINCT FROM and NULLs
От:
Richard Guo <guofenglinux@gmail.com>
Дата:
On Mon, Jul 11, 2022 at 10:36 PM PG Bug reporting form <noreply@postgresql.org> wrote:
Hi,
It appears that selectivity for "IS NOT DISTINCT FROM" clauses regard the
proportion of NULLs in the same way as "=", leading to polar opposite row
count
estimates.
In practice this causes nested loop joins to be used when that is not
appropriate. Not sure if this is a known issue, but I was unable to find
any
previous mentions of it.
# EXPLAIN SELECT FROM test x, test y WHERE x.a IS DISTINCT FROM y.a;
QUERY PLAN
----------------------------------------------------------------------
Nested Loop (cost=0.00..15030.50 rows=1000000 width=0)
Join Filter: (x.a IS DISTINCT FROM y.a)
-> Seq Scan on test x (cost=0.00..14.00 rows=1000 width=4)
-> Materialize (cost=0.00..19.00 rows=1000 width=4)
-> Seq Scan on test y (cost=0.00..14.00 rows=1000 width=4)
(5 rows)
DistinctExpr has the same representation as OpExpr with operator "=". So
we estimate its selectivity just as if it is 'x.a = y.a', and then
invert the result.
For OpExpr 'x.a = y.a', because no MCV lists are available, we estimate
its selectivity as MIN(1/nd1,1/nd2)*(1-nullfrac1)*(1-nullfrac2). Note
that both nullfrac1 and nullfrac2 are 100% in the case, so the
selectivity is calculated as zero, and the inverted result is 1, which
is for DistinctExpr.
The comment in the codes has explained this behavior, as it says:
/*
* DistinctExpr has the same representation as OpExpr, but the
* contained operator is "=" not "<>", so we must negate the result.
* This estimation method doesn't give the right behavior for nulls,
* but it's better than doing nothing.
*/
if (IsA(clause, DistinctExpr))
s1 = 1.0 - s1;
So maybe this is a known issue?
Thanks
Richard
Re: BUG #17545: Incorrect selectivity for IS NOT DISTINCT FROM and NULLs
От:
Tom Lane <tgl@sss.pgh.pa.us>
Дата:
Richard Guo writes: > The comment in the codes has explained this behavior, as it says: > * This estimation method doesn't give the right behavior for nulls, > * but it's better than doing nothing. > So maybe this is a known issue? It's a nobodys-bothered-to-make-it-better issue. In general, PG's treatment of IS [NOT] DISTINCT FROM is pretty lame --- for example, you might wish that IS NOT DISTINCT FROM could use an index in the way that "=" can, but that's never been made to happen. regards, tom lane
Re: BUG #17545: Incorrect selectivity for IS NOT DISTINCT FROM and NULLs
Hi,
like "=", so row pairs with NULL on both sides are never counted. The
patch adds the product of the two null fractions to the "=" estimate.
Two tables of 2000 rows, 30% NULL, joined on
x.a IS NOT DISTINCT FROM y.a:
master rows=1400 actual rows=361400
patched rows=361400 actual rows=361400
x.a IS NOT DISTINCT FROM y.a:
master rows=1400 actual rows=361400
patched rows=361400 actual rows=361400
Thanks,
Shihao
Re: BUG #17545: Incorrect selectivity for IS NOT DISTINCT FROM and NULLs
Hi Shihao, Thanks for picking this up. I tested v1 on master (a464d31ff6). It builds without warnings, the regression tests pass, and no existing plan changes. Estimated vs actual rows, on two 2000-row tables with 30% NULLs and on the report's 1000 all-NULL rows: master v1 actual JOIN ON a IS NOT DISTINCT FROM 28000 388000 388000 JOIN ON a IS DISTINCT FROM 3972000 3612000 3612000 LEFT JOIN, IS NOT DISTINCT FROM 28000 388000 388700 report, all NULLs 1 1000000 1000000 IS DISTINCT FROM, which Richard pointed out has the same problem, is fixed as well. That may be worth a sentence in the commit message, which only describes the IS NOT DISTINCT FROM side. EXISTS and NOT EXISTS are still off, since 0001 leaves semijoins and antijoins alone: master v1 actual EXISTS 700 700 1300 NOT EXISTS 1300 1300 700 I think they're worth handling in the same patch. NOT EXISTS with IS NOT DISTINCT FROM is a common way to find rows missing from another table when NULLs should match. It also affects costing: compute_semi_anti_join_factors() divides the inner join estimate, which v1 raises, by the semijoin estimate, which it doesn't change. So the average number of matches per matching outer row goes from 40 on master to 554 with v1, against 298.5 actual. The attached patch on top of v1 handles them (it's a .txt, so cfbot stays on v1). For a semijoin or antijoin the "=" estimate is the fraction of outer rows that have a match, so it adds the fraction of outer rows whose input is NULL, since they all have a match if any inner row's input is NULL. It assumes there is one if it expects at least one, and scales down if it expects fewer. The two cases above then come out at 1300 and 700, and the average matches at 298.5. It adds two tests on your tables: v1 v1+patch actual EXISTS 70 170 170 NOT EXISTS 130 30 30 It works where the NOT around the DistinctExpr is estimated, not in the DistinctExpr branch. A plain IS DISTINCT FROM inside EXISTS is estimated as the complement of the IS NOT DISTINCT FROM estimate, so changing the DistinctExpr branch would lower that one too, and it is already too low (1300 against 2000 actual rows). With the patch it doesn't change. I also tried the arguments in either order, an extra key column, all-NULL tables and the inner side cut to 200 rows, and those match the actual rows too. With the inner side cut to 2 rows it's 388 against 600 (28 with v1). With NULLs on only one side nothing changes, as expected. One case neither version gets right is two columns of the same table whose NULLs are in the same rows: 330 against 2000 actual rows (10 on master), since the two null fractions are taken as independent. I don't think that needs handling here. Regards, Rahul Yadav
Re: BUG #17545: Incorrect selectivity for IS NOT DISTINCT FROM and NULLs
Hi Rahul,
Thanks for testing, and for the patch. I agree that EXISTS and NOT
EXISTS should be handled too.
v2 is attached, with your patch merged in and you as co-author. The
commit message of 0001 now mentions IS DISTINCT FROM too.
My test get the same numbers as you.
Thanks for testing, and for the patch. I agree that EXISTS and NOT
EXISTS should be handled too.
v2 is attached, with your patch merged in and you as co-author. The
commit message of 0001 now mentions IS DISTINCT FROM too.
My test get the same numbers as you.
Thanks,
Shihao
Re: BUG #17545: Incorrect selectivity for IS NOT DISTINCT FROM and NULLs
От:
Rahul <rahul@rhyadav.dev>
Дата:
Hi Shihao, Thanks for merging it. v2 gives exactly the same code as v1 plus my patch, which is what I tested, and it applies cleanly to current master. Could you add it to the next commitfest so it doesn't get lost? Regards, Rahul Yadav
Re: BUG #17545: Incorrect selectivity for IS NOT DISTINCT FROM and NULLs
От:
shihao zhong <zhong950419@gmail.com>
Дата:
Re: BUG #17545: Incorrect selectivity for IS NOT DISTINCT FROM and NULLs
От:
Greg Burd <greg@burd.me>
Дата:
On Mon, 5 Oct 2026 14:38:05 -0400, shihao zhong wrote: > Hi Rahul, > > https://commitfest.postgresql.org/patch/7396/ > > Thanks, > Shihao Hey Shihao, First off, thanks for working on this. This issue caught my attention, so I measured the selectivity error this fixes in an effort to quantify the size of it, and it turns out to be large in the join case. I tested on master at the patch's merge-base (126976a8ffc) and master+v2. For a join on t1.a IS NOT DISTINCT FROM t2.a, where both columns carry NULLs, the estimate must count NULL-NULL pairs as matching (NULL IS NOT DISTINCT FROM NULL is true). So I had a solver run a differential selectivity check over 120 randomized two-table joins with varied NULL fractions and distinct counts, estimate vs actual rows: master: worst case off by 4915x master+v2: worst case 1.0x (exact on every case I generated) The ScalarArrayOp sibling the patch also touches, col <> ALL (ARRAY[.. NULL]), estimates within 1.5x of actual on the patched build. One note on reproducing it: the error is specific to the join path. My first attempt used IS NOT DISTINCT FROM as a scalar filter (WHERE a IS NOT DISTINCT FROM ), where master already estimates well, so a scalar-only test would wrongly suggest nothing was wrong. The patch's planner_est.sql exercises the join form, which is where the 4915x comes from. +1 for the patch. best. -greg
Re: BUG #17545: Incorrect selectivity for IS NOT DISTINCT FROM and NULLs
Hi,
Building on Shihao's patch and Rahul's analysis, I would like to propose
this implementation for NULL-safe join estimates, including the IS
DISTINCT FROM SEMI/ANTI case Rahul identified. It also fixes a related
ordinary <> misestimate, which I suggest reviewing here under BUG #17545.
A particularly clear ordinary <> example is statement 6 of not_eq_x1.sql
in the local test suite, run against the xman4 database:
EXPLAIN ANALYZE
SELECT FROM t_test1 x INNER JOIN t_test1 y ON x.c2 <> y.c3;
The table has 1,000 rows and c3 is entirely NULL. The reported master
estimate is 1,000,000 rows; the actual result is zero. The patched result
recorded for that statement is:
Master estimate Patched estimate Actual rows
1000000 1 0
Every comparison with y.c3 yields UNKNOWN, so no pair satisfies strict <>.
The corrected selectivity is zero; the displayed estimate of one comes
from the planner's minimum row estimate. The comma-join spelling in
statement 2 of the same SQL file gives the same patched result.
The c2 column contains 600 NULLs, 200 ones and 200 twos. The c2 self-joins
in statement 6 of the four *_x0.sql files give these recorded results:
Predicate Patched estimate Actual rows
= 80000 80000
<> 80000 80000
IS NOT DISTINCT FROM 440000 440000
IS DISTINCT FROM 560000 560000
The ordinary 1 - E formula would instead estimate the <> case at 920,000.
For non-SEMI/ANTI inner and outer join clauses, let E be the existing
ordinary equality pair selectivity, n1/n2 the input NULL fractions, and
B = (1 - n1) * (1 - n2) the fraction of pairs with two non-NULL inputs.
The intended estimates are:
= E
<> B - E
IS NOT DISTINCT FROM E + n1 * n2
IS DISTINCT FROM 1 - E - n1 * n2
SEMI/ANTI joins instead use S, the fraction of outer rows with at least
one inner partner. Statement 17 of eq_x0.sql and not_eq_x0.sql tests
x.c1 = y.c1 and x.c1 <> y.c1 inside EXISTS. Both queries are estimated at
1,000 rows and actually return 1,000. Every outer value has both an equal
and an unequal inner partner; complementing the equality SEMI estimate
would therefore give the wrong S for inequality.
The actual SEMI/ANTI statements 18 and 22 of the four *_x1.sql files,
using x.c2 and the all-NULL y.c3, also distinguish the NULL rules:
Predicate SEMI estimate/actual ANTI estimate/actual
= 1/0 1000/1000
<> 1/0 1000/1000
IS NOT DISTINCT FROM 600/600 400/400
IS DISTINCT FROM 400/400 600/600
The two 1/0 entries again reflect the minimum row estimate.
The implementation works as follows:
1. clausesel.c recognizes NULL-safe join clauses and passes their context
through nullsafe_join_selectivity(). Only the recognized built-in
eqjoinsel/neqjoinsel procedures receive an optional sixth boolean
argument, null_safe_compare. Other procedures keep their five-argument
calling convention and legacy dispatch. IS DISTINCT FROM uses the
inequality negator only when the operator pair uses those built-in
estimators.
2. eqjoinsel() preserves ordinary = estimates and adds NULL contributions
for IS NOT DISTINCT FROM only when null_safe_compare is enabled.
Non-SEMI/ANTI joins return E + n1 * n2. For SEMI/ANTI, add NULL partners
to the existing non-NULL equality existence estimate S_eq:
S = S_eq + n_outer * min(n_inner * N_inner, 1)
Here n_outer/n_inner are the outer/inner NULL fractions, and N_inner is
the effective inner row estimate. Return S = 0 for a provably empty
inner input, reset S_eq to zero for an all-NULL inner input, and retain
the existing bound based on the inner-join estimate. eqjoinsel_inner()
and eqjoinsel_semi() retain their original algorithms and signatures,
with only their MCV matcher calls adapted. The shared match count
continues to describe only non-NULL MCV pairs.
3. For non-SEMI/ANTI joins, neqjoinsel() uses B - E for ordinary <> and
complements the NULL-safe eqjoinsel() estimate for IS DISTINCT FROM,
giving 1 - E - n1 * n2. Its SEMI/ANTI path uses distinctjoinsel_semi()
and distinctjoinsel_semi_internal() to estimate S separately under
ordinary or NULL-safe semantics, rather than simply complementing
equality existence. Optional equality match indices identify the
inner MCV equal to each outer MCV; the estimator checks for other MCVs,
NULLs where allowed, and residual values. It retains the existing hash
matching support and leaves the original statistics slots unchanged.
Both SEMI/ANTI estimators return S; the existing caller uses S and 1 - S
for SEMI and ANTI output rows, respectively.
The upper-level NULL correction discussed earlier is reasonable when the
underlying estimator returns ordinary equality selectivity. This patch
makes that distinction explicit for the built-in estimators. In the
unpatched code, IS DISTINCT FROM still uses the equality estimator followed
by an upper-level complement, so fixing ordinary neqjoinsel() alone does
not break that existing route. The extra context is needed by the route
chosen here, where <> and IS DISTINCT FROM share neqjoinsel() and the same
operator OID. The optional sixth argument is an interface proposal for
review, rather than a prerequisite for fixing ordinary <> separately.
This local snapshot is v3.1.me.5, based on commit
1d657c6e013e152ed37b42a22ee9f291179ee50f. It adds regression coverage
for the NULL rules, residual values, absent MCV lists, cross-type matching
and custom estimator procedures, and updates one existing join order
following the ordinary <> correction.
The numerical results above come from the original SQL suite in
~/4_patch/test_distint_from: eq_x[0-3].sql, not_eq_x[0-3].sql,
is_not_distinct_from_x[0-3].sql and is_distinct_from_x[0-3].sql. The saved
run has 16 files and 384 statements, classified by their actual SQL text:
Join type Queries Exact Zero-row floor Other differences
INNER 128 94 34 0
SEMI 72 53 19 0
ANTI 56 36 20 0
LEFT 64 41 0 23
RIGHT 64 41 0 23
Total 384 265 73 46
All actual row counts agree with counts independently calculated from
the table's value frequencies. INNER, SEMI and ANTI estimates are exact
apart from the zero-row floor. The remaining 46 differences are LEFT/RIGHT
outer-join padding estimates. No statistics on the original table were
recollected. The results were unchanged by moving NULL handling into
eqjoinsel(). Subsequent edits standardized the null_safe_compare parameter
name, clarified comments, and reduced duplicate regression cases. The
targeted planner_est regression passes. The supplied selected-tests.sql
and saved result records identify the original files and statement numbers
used above.
The patch does not reconstruct filtered inner distributions or resolve
all uncertainty about missing statistics and residual-value overlap.
Outer-join padding remains approximate, as the suite shows. This work
changes join estimates; restriction estimates and executor/index support
are outside its scope.
I would appreciate feedback on the estimator interface and dispatch, and
on the SEMI/ANTI heuristics. I suggest keeping the ordinary <> reproduction
and the NULL-safe estimation changes together for review in this thread.
Discussion: https://www.postgresql.org/message-id/flat/17545-a0ca4de888953169%40postgresql.org
CommitFest: https://commitfest.postgresql.org/patch/7396/
Attached is an alternative implementation for discussion. It is not intended to supersede the current
Ready for Committer patch at this stage.
I will also report the selectivity misestimation for ordinary <> separately and prepare a separate patch,
so that this issue can be reviewed independently.
The attached test materials cover ordinary = and <> comparisons, NULL-safe IS [NOT] DISTINCT FROM
comparisons, and various join types:
- setup.sql — test data setup
- test_sql.tar — test SQL files
- test_result.xlsx — test results
regards,
--
ZizhuanLiu (X-MAN)
44973863@qq.com