Incorrect selectivity estimates for NOT on nullable boolean columns
Incorrect selectivity estimates for NOT on nullable boolean columns
Hi everyone,
I noticed that clause_selectivity_ext() estimates `NOT A` as `1 - selectivity(A)`, without accounting for NULL values.
For example:
```
CREATE TABLE t (b BOOLEAN);
--- 70% - NULLs, 20% - true, 10% - false
INSERT INTO t
SELECT CASE
WHEN i <= 7000 THEN NULL::boolean
WHEN i <= 9000 THEN TRUE
ELSE FALSE
END
FROM generate_series(1, 10000) AS g(i);
ANALYZE t;
EXPLAIN ANALYZE SELECT * FROM t WHERE NOT b;
QUERY PLAN
------------------------------------------------------------------------------------------------------
Seq Scan on t (cost=0.00..138.00 rows=8000 width=5) (actual time=2.278..2.379 rows=1000.00 loops=1)
Filter: (NOT b)
Rows Removed by Filter: 9000
Buffers: shared read=38
Planning:
Buffers: shared hit=15 read=12 dirtied=1
Planning Time: 0.651 ms
Execution Time: 2.511 ms
(8 rows)
```
Query returns 1000 rows. However, the the estimated rows 8000.
I propose checking whether statistics are available for the argumnet of NOT. If so, we can use `booltestsel(IS_FALSE)`, which accounts for the null fraction. Otherwise, we retain the existing estimate.
The plan after fix:
```
EXPLAIN ANALYZE SELECT * FROM t WHERE NOT b;
QUERY PLAN
------------------------------------------------------------------------------------------------------
Seq Scan on t (cost=0.00..138.00 rows=1000 width=5) (actual time=0.753..0.830 rows=1000.00 loops=1)
Filter: (NOT b)
Rows Removed by Filter: 9000
Buffers: shared hit=75 dirtied=1 written=1
Planning:
Buffers: shared hit=21
Planning Time: 0.109 ms
Execution Time: 0.861 ms
(8 rows)
```
Does this approach seem reasonable?
--
Best regards,
Ilia Evdokimov,
Tantor Labs LLC,
https://tantorlabs.com/
Re: Incorrect selectivity estimates for NOT on nullable boolean columns
The following review has been posted through the commitfest application: make installcheck-world: tested, passed Implements feature: tested, failed Spec compliant: not tested Documentation: not tested Hello, This patch looks good to me. Maybe you could add some regression-test coverage ? I don't think that SQL compliance must be checked or that documentation should be updated. Regards, PF. The new status of this patch is: Ready for Committer
Re: Incorrect selectivity estimates for NOT on nullable boolean columns
Hi,
I have applied the proposed patch and tested the issue related to incorrect selectivity estimates for NOT on nullable Boolean columns.
I first reproduced the issue before applying the patch. The test table contained 10,000 rows (7,000 NULL, 2,000 TRUE, and 1,000 FALSE values).
Before applying the patch:
Estimated rows: 8,000
Actual rows: 1,000
After applying the patch, I rebuilt and tested PostgreSQL using the same data and query.
After applying the patch:
Estimated rows: 1,000
Actual rows: 1,000
Rows removed by filter: 9,000
Execution time: 0.803 ms
I also tested cases with no NULL values, only NULL values, and without ANALYZE statistics.
All regression tests passed, and git diff --check reported no issues.
The estimated row count now matches the actual row count in the main test case.
Regards
solai
Re: Incorrect selectivity estimates for NOT on nullable boolean columns
Hi Ilia,
Thank you for finding this issue and for fixing the patch.
I've reviewed the patch and run some tests.
When I try WHERE b = false, the parser also represents it as an is_notclause (a BoolExpr with NOT_EXPR),
just as it does for WHERE NOT b.
The original semantic logic is:
s1 = 1.0 - clause_selectivity_ext(root, arg, ...);
In other words, clause_selectivity_ext(root, arg, ...) is expected to return the selectivity of the underlying clause being TRUE
, so we subtract it from 1.0 to obtain the selectivity of the FALSE case.
To preserve this original semantic behavior, I can think of two approaches. I tested them , and all two are relatively straightforward
and provide a consistent way to handle the logic as patch does.
[1]. Call booltestsel() in selfuncs.c directly and delegate the logic to booltestsel(IS_FALSE):
s1 = booltestsel(root, IS_FALSE, arg, varRelid, jointype, sjinfo);
The main logic of booltestsel() is:
[1.1] When statistics are available, it applies the relevant IS_FALSE logic.
[1.2] When statistics are unavailable, it still falls back to: 1.0 - (double) clause_selectivity()
Since clause_selectivity() unconditionally calls clause_selectivity_ext() without any additional transformation, this is equivalent to:
1.0 - (double) clause_selectivity_ext(..., true)
[2]. Construct a BooleanTest(IS_FALSE) node and delegate the processing to the existing BooleanTest handling
in the else if (IsA(clause, BooleanTest)) branch of clause_selectivity_ext():
BooleanTest *booltest = makeNode(BooleanTest);
booltest->arg = get_notclausearg((Expr *) clause);
booltest->booltesttype = IS_FALSE;
booltest->location = -1;
s1 = clause_selectivity_ext(root,
(Node *) booltest,
varRelid,
jointype,
sjinfo,
use_extended_stats);
Abouting patch:
[3]. Keep the handling within the current if branch and split the logic of booltestsel() between the two cases:
Node *arg = (Node *) get_notclausearg((Expr *) clause);
VariableStatData vardata;
examine_variable(root, arg, varRelid, &vardata);
if (HeapTupleIsValid(vardata.statsTuple))
{
/* Use statistics to select FALSE values, excluding NULLs. */
s1 = booltestsel(root, IS_FALSE, arg, varRelid, jointype, sjinfo);
}
else
{
/* Otherwise, estimate the underlying clause */
s1 = 1.0 - clause_selectivity_ext(root, arg,
varRelid,
jointype,
sjinfo,
use_extended_stats);
}
ReleaseVariableStats(vardata);
In the patch, case [1.1] is used when statistics are available, while case [1.2] is handled directly when statistics are unavailable.
After testing them, my understanding is that all three approaches produce the same selectivity estimates in both cases:
when statistics are available and when they are not.
The main differences are where the responsibility for handling this logic resides:
- [2] keeps the handling within the current clause_selectivity_ext() function by constructing a BooleanTest node.
- [1] delegates the handling to booltestsel(IS_FALSE) in selfuncs.c.
- [3] keeps the handling within the current if branch and reimplements the relevant parts of booltestsel() locally.
This avoids the additional call chain booltestsel() -> clause_selectivity() -> clause_selectivity_ext() when
statistics are unavailable, while retaining the same logic.
Personally, I prefer approach [1]. I think centralizing the semantics in booltestsel() could help keep the handling consistent,
reduce maintenance overhead, and make future extensions to the function easier to manage.
Please let me know if I've overlooked anything or if you see any issues with this reasoning.
What do you think?
regards,
--
ZizhuanLiu (X-MAN)
44973863@qq.com
Re: Incorrect selectivity estimates for NOT on nullable boolean columns
On 11/11/26 14:37, ZizhuanLiu X-MAN wrote: > The main differences are where the responsibility for handling this logic resides: > - [2] keeps the handling within the current clause_selectivity_ext() function by constructing a BooleanTest node. > > - [1] delegates the handling to booltestsel(IS_FALSE) in selfuncs.c. > > - [3] keeps the handling within the current if branch and reimplements the relevant parts of booltestsel() locally. > This avoids the additional call chain booltestsel() -> clause_selectivity() -> clause_selectivity_ext() when > statistics are unavailable, while retaining the same logic. > > Personally, I prefer approach [1]. I think centralizing the semantics in booltestsel() could help keep the handling consistent, > reduce maintenance overhead, and make future extensions to the function easier to manage. > > Please let me know if I've overlooked anything or if you see any issues with this reasoning. > > What do you think? I don't think approaches [1] and [2] are equivalent to [3] in all cases. The difference is in the fallback path when no statistics tuple is available for the argument of NOT. In [3], the recursive call preserves the caller's `use_extended_stats` value: ``` s1 = 1.0 - clause_selectivity_ext(..., use_extended_stats); ``` In [1], `booltestsel()` instead calls `clause_selectivity()`, which calls `clause_selectivity_ext()` with use_extended_stats = true: ``` booltestsel(IS_FALSE, arg) -> clause_selectivity(arg, ...) -> clause_selectivity_ext(arg, ..., true) ``` Therefore, if the original call had use_extended_stats = false, [1] can enable extended statistics when estimating the argument. Approach [2] has the same issue. For that reason, I think v1 patch is needed to preserve the existing behavior. -- Best regards, Ilia Evdokimov, Tantor Labs LLC, https://tantorlabs.com/