Hi Zsolt,

Thank you for testing and for the reproductions.

On 12/4/26 01:36, Zsolt Parragi wrote:
1. DISTINCT with 100% true 50% not true

CREATE TABLE t AS SELECT true AS a, i AS b FROM
generate_series(1,10000) AS g(i);
ANALYZE t;
EXPLAIN ANALYZE WITH s AS MATERIALIZED (SELECT DISTINCT a,b FROM t)
SELECT * FROM s WHERE NOT a;
-- patched: CTE Scan on s ... rows=5000 ... actual rows=0.00
-- master:  CTE Scan on s ... rows=1    ... actual rows=0.00

In this case, the statistics for the CTE output do not contain MCV frequencies: DISTINCT can change the frequency distribution, so those frequencies are discarded. Without them, booltestsel(IS_FALSE) assumes an even split between TRUE and FALSE.

I changed the NOT estimate to use boolvarsel() for the TRUE fraction and subtract both that estimate and the NULL fraction from 1. This allows the estimate to use the number of distinct values when MCV frequencies are unavailable.

With this change, the estimate for your example is back to 1 row, as on master. This addresses the reported regression, although it does not generally solve estimation after DISTINCT when the values themselves are no longer available in the statistics.

2. NOT inside BooleanTest (IS FALSE / IS NOT FALSE) regresses on
nullable booleans

CREATE TABLE t (id int, deleted boolean) WITH (autovacuum_enabled = off);
INSERT INTO t
SELECT i, CASE WHEN i <= 9500 THEN NULL WHEN i <= 9900 THEN true ELSE false END
FROM generate_series(1, 10000) AS g(i);
ANALYZE t;
CREATE VIEW v AS SELECT id, NOT deleted AS active FROM t;

EXPLAIN ANALYZE SELECT * FROM v WHERE active IS FALSE;
-- patched: rows=9900 (actual rows=400.00)
-- master:  rows=400  (actual rows=400.00)

EXPLAIN ANALYZE SELECT * FROM v WHERE active IS NOT FALSE;
-- patched: rows=100  (actual rows=9600.00)
-- master:  rows=9600 (actual rows=9600.00)

The issue here is in the fallback path of booltestsel(). When it has no statistics for the NOT expression itself, it estimates the test using the selectivity of that expression or its complement. After the patch, the selectivity of NOT excludes NULLs, so this no longer gives the correct result for BooleanTest cases that include NULLs or take the complement.

I added handling for NOT in that fallback path: the BooleanTest is converted to the equivalent test on the argument of NOT. For example, (NOT deleted) IS FALSE is estimated as deleted IS TRUE, and (NOT deleted) IS NOT FALSE as deleted IS NOT TRUE.

With this change, the estimates for your examples are 400 and 9600 rows, respectively, matching the actual row counts.

I also added regression tests for both reported cases, the original NOT on a nullable Boolean column, and all six BooleanTest types over NOT. The test_setup and stats_ext regression tests pass.

Does this approach look reasonable?

--
Best regards,
Ilia Evdokimov,
Tantor Labs LLC,
https://tantorlabs.com/
From 11e0431fcafbd90f99d29128bc59b7bea8fb4d44 Mon Sep 17 00:00:00 2001
From: Ilia Evdokimov <[email protected]>
Date: Fri, 4 Dec 2026 12:32:30 +0300
Subject: [PATCH v3] Fix NOT selectivity estimates for nullable boolean
 expressions

Account for NULL values when estimating NOT over a boolean expression.
When statistics are available, subtract both the estimated TRUE
fraction and the NULL fraction from 1. Otherwise, retain the existing
recursive estimate.

Fix the corresponding issue in multivariate MCV estimates: inverting
a match bitmap for a boolean column or expression also matches NULL
values. Check MCV values directly for FALSE instead.

When estimating a BooleanTest over NOT without statistics for the NOT
expression, estimate the equivalent test on its argument. This avoids
incorrect estimates caused by treating NULL as the complement of TRUE
or FALSE.
---
 src/backend/optimizer/path/clausesel.c  | 27 ++++++--
 src/backend/statistics/mcv.c            | 25 +++++++
 src/backend/utils/adt/selfuncs.c        | 27 ++++++++
 src/test/regress/expected/stats_ext.out | 92 +++++++++++++++++++++++++
 src/test/regress/sql/stats_ext.sql      | 40 +++++++++++
 5 files changed, 204 insertions(+), 7 deletions(-)

diff --git a/src/backend/optimizer/path/clausesel.c b/src/backend/optimizer/path/clausesel.c
index c22cbfc9ca0..38a5437f67d 100644
--- a/src/backend/optimizer/path/clausesel.c
+++ b/src/backend/optimizer/path/clausesel.c
@@ -14,6 +14,8 @@
  */
 #include "postgres.h"
 
+#include "access/htup_details.h"
+#include "catalog/pg_statistic.h"
 #include "nodes/nodeFuncs.h"
 #include "optimizer/clauses.h"
 #include "optimizer/optimizer.h"
@@ -803,13 +805,24 @@ clause_selectivity_ext(PlannerInfo *root,
 	}
 	else if (is_notclause(clause))
 	{
-		/* inverse of the selectivity of the underlying clause */
-		s1 = 1.0 - clause_selectivity_ext(root,
-										  (Node *) get_notclausearg((Expr *) clause),
-										  varRelid,
-										  jointype,
-										  sjinfo,
-										  use_extended_stats);
+		Node	   *arg = (Node *) get_notclausearg((Expr *) clause);
+		VariableStatData vardata;
+
+		examine_variable(root, arg, varRelid, &vardata);
+		if (HeapTupleIsValid(vardata.statsTuple))
+		{
+			/* Use the expression's statistics for TRUE and NULL values. */
+			s1 = 1.0 - boolvarsel(root, arg, varRelid) -
+				((Form_pg_statistic) GETSTRUCT(vardata.statsTuple))->stanullfrac;
+		}
+		else
+			s1 = 1.0 - clause_selectivity_ext(root, arg,
+											  varRelid,
+											  jointype,
+											  sjinfo,
+											  use_extended_stats);
+		ReleaseVariableStats(vardata);
+		CLAMP_PROBABILITY(s1);
 	}
 	else if (is_andclause(clause))
 	{
diff --git a/src/backend/statistics/mcv.c b/src/backend/statistics/mcv.c
index e504d56079f..5efd0f6f868 100644
--- a/src/backend/statistics/mcv.c
+++ b/src/backend/statistics/mcv.c
@@ -1890,12 +1890,37 @@ mcv_get_match_bitmap(PlannerInfo *root, List *clauses,
 
 			BoolExpr   *not_clause = ((BoolExpr *) clause);
 			List	   *not_args = not_clause->args;
+			Node	   *arg;
 
 			/* match/mismatch bitmap for each MCV item */
 			bool	   *not_matches = NULL;
 
 			Assert(not_args != NIL);
 			Assert(list_length(not_args) == 1);
+			arg = linitial(not_args);
+
+			if (IsA(arg, RelabelType))
+				arg = (Node *) ((RelabelType *) arg)->arg;
+
+			/*
+			 * For a bare boolean variable or expression, test for FALSE
+			 * directly.  Inverting a match bitmap would also match NULLs.
+			 */
+			if (!is_opclause(arg) && !IsA(arg, ScalarArrayOpExpr) &&
+				!IsA(arg, NullTest) && !IsA(arg, BoolExpr))
+			{
+				int			idx = mcv_match_expression(arg, keys, exprs, NULL);
+
+				for (uint32 i = 0; i < mcvlist->nitems; i++)
+				{
+					MCVItem    *item = &mcvlist->items[i];
+					bool		match = !item->isnull[idx] &&
+						!DatumGetBool(item->values[idx]);
+
+					matches[i] = RESULT_MERGE(matches[i], is_or, match);
+				}
+				continue;
+			}
 
 			/* build the match bitmap for the NOT-clause */
 			not_matches = mcv_get_match_bitmap(root, not_args, keys, exprs,
diff --git a/src/backend/utils/adt/selfuncs.c b/src/backend/utils/adt/selfuncs.c
index 5ee377595bd..377b9fb746a 100644
--- a/src/backend/utils/adt/selfuncs.c
+++ b/src/backend/utils/adt/selfuncs.c
@@ -1732,6 +1732,33 @@ booltestsel(PlannerInfo *root, BoolTestType booltesttype, Node *arg,
 			}
 		}
 	}
+	else if (is_notclause(arg))
+	{
+		/* NOT exchanges TRUE and FALSE, but leaves NULL unchanged. */
+		switch (booltesttype)
+		{
+			case IS_TRUE:
+				booltesttype = IS_FALSE;
+				break;
+			case IS_NOT_TRUE:
+				booltesttype = IS_NOT_FALSE;
+				break;
+			case IS_FALSE:
+				booltesttype = IS_TRUE;
+				break;
+			case IS_NOT_FALSE:
+				booltesttype = IS_NOT_TRUE;
+				break;
+			case IS_UNKNOWN:
+			case IS_NOT_UNKNOWN:
+				break;
+			default:
+				elog(ERROR, "unrecognized booltesttype: %d", (int) booltesttype);
+		}
+		selec = booltestsel(root, booltesttype,
+							(Node *) get_notclausearg((Expr *) arg),
+							varRelid, jointype, sjinfo);
+	}
 	else
 	{
 		/*
diff --git a/src/test/regress/expected/stats_ext.out b/src/test/regress/expected/stats_ext.out
index decdca0c161..4fa7ae7947b 100644
--- a/src/test/regress/expected/stats_ext.out
+++ b/src/test/regress/expected/stats_ext.out
@@ -1944,6 +1944,98 @@ SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies_multi
 
 DROP TABLE functional_dependencies_multi;
 -- MCV lists
+-- NOT must not match NULL values in a multivariate MCV list.
+CREATE TABLE mcv_not_test (a boolean, b integer) WITH (autovacuum_enabled = off);
+INSERT INTO mcv_not_test
+SELECT CASE WHEN i <= 400 THEN false WHEN i <= 800 THEN NULL ELSE true END,
+       CASE WHEN i <= 800 THEN 1 ELSE 2 END
+FROM generate_series(1, 1000) AS s(i);
+CREATE STATISTICS mcv_not_stats (mcv) ON a, b FROM mcv_not_test;
+ANALYZE mcv_not_test;
+SELECT * FROM check_estimated_rows('SELECT * FROM mcv_not_test WHERE NOT a AND b = 1');
+ estimated | actual 
+-----------+--------
+       400 |    400
+(1 row)
+
+SELECT * FROM check_estimated_rows('SELECT * FROM mcv_not_test WHERE NOT a OR b = 1');
+ estimated | actual 
+-----------+--------
+       800 |    800
+(1 row)
+
+DROP STATISTICS mcv_not_stats;
+CREATE STATISTICS mcv_not_stats (mcv) ON (nullif(a, true)), b FROM mcv_not_test;
+ANALYZE mcv_not_test;
+SELECT * FROM check_estimated_rows('SELECT * FROM mcv_not_test WHERE NOT nullif(a, true) AND b = 1');
+ estimated | actual 
+-----------+--------
+       400 |    400
+(1 row)
+
+DROP TABLE mcv_not_test;
+-- NOT must use the number of distinct values when grouping removes MCVs.
+CREATE TABLE not_grouped_test (a boolean, b integer) WITH (autovacuum_enabled = off);
+INSERT INTO not_grouped_test SELECT true, i FROM generate_series(1, 10000) AS g(i);
+ANALYZE not_grouped_test;
+SELECT * FROM check_estimated_rows('WITH s AS MATERIALIZED (SELECT DISTINCT a, b FROM not_grouped_test) SELECT * FROM s WHERE NOT a');
+ estimated | actual 
+-----------+--------
+         1 |      0
+(1 row)
+
+DROP TABLE not_grouped_test;
+-- Boolean tests of NOT must preserve the three-valued logic of NULL.
+CREATE TABLE not_bool_test (id integer, deleted boolean) WITH (autovacuum_enabled = off);
+INSERT INTO not_bool_test
+SELECT i, CASE WHEN i <= 9500 THEN NULL WHEN i <= 9900 THEN true ELSE false END
+FROM generate_series(1, 10000) AS g(i);
+ANALYZE not_bool_test;
+SELECT * FROM check_estimated_rows('SELECT * FROM not_bool_test WHERE NOT deleted');
+ estimated | actual 
+-----------+--------
+       100 |    100
+(1 row)
+
+CREATE VIEW not_bool_view AS SELECT id, NOT deleted AS active FROM not_bool_test;
+SELECT * FROM check_estimated_rows('SELECT * FROM not_bool_view WHERE active IS TRUE');
+ estimated | actual 
+-----------+--------
+       100 |    100
+(1 row)
+
+SELECT * FROM check_estimated_rows('SELECT * FROM not_bool_view WHERE active IS NOT TRUE');
+ estimated | actual 
+-----------+--------
+      9900 |   9900
+(1 row)
+
+SELECT * FROM check_estimated_rows('SELECT * FROM not_bool_view WHERE active IS FALSE');
+ estimated | actual 
+-----------+--------
+       400 |    400
+(1 row)
+
+SELECT * FROM check_estimated_rows('SELECT * FROM not_bool_view WHERE active IS NOT FALSE');
+ estimated | actual 
+-----------+--------
+      9600 |   9600
+(1 row)
+
+SELECT * FROM check_estimated_rows('SELECT * FROM not_bool_view WHERE active IS UNKNOWN');
+ estimated | actual 
+-----------+--------
+      9500 |   9500
+(1 row)
+
+SELECT * FROM check_estimated_rows('SELECT * FROM not_bool_view WHERE active IS NOT UNKNOWN');
+ estimated | actual 
+-----------+--------
+       500 |    500
+(1 row)
+
+DROP VIEW not_bool_view;
+DROP TABLE not_bool_test;
 CREATE TABLE mcv_lists (
     filler1 TEXT,
     filler2 NUMERIC,
diff --git a/src/test/regress/sql/stats_ext.sql b/src/test/regress/sql/stats_ext.sql
index c4771535f2c..e93ecf375bf 100644
--- a/src/test/regress/sql/stats_ext.sql
+++ b/src/test/regress/sql/stats_ext.sql
@@ -960,6 +960,46 @@ SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies_multi
 DROP TABLE functional_dependencies_multi;
 
 -- MCV lists
+-- NOT must not match NULL values in a multivariate MCV list.
+CREATE TABLE mcv_not_test (a boolean, b integer) WITH (autovacuum_enabled = off);
+INSERT INTO mcv_not_test
+SELECT CASE WHEN i <= 400 THEN false WHEN i <= 800 THEN NULL ELSE true END,
+       CASE WHEN i <= 800 THEN 1 ELSE 2 END
+FROM generate_series(1, 1000) AS s(i);
+CREATE STATISTICS mcv_not_stats (mcv) ON a, b FROM mcv_not_test;
+ANALYZE mcv_not_test;
+SELECT * FROM check_estimated_rows('SELECT * FROM mcv_not_test WHERE NOT a AND b = 1');
+SELECT * FROM check_estimated_rows('SELECT * FROM mcv_not_test WHERE NOT a OR b = 1');
+DROP STATISTICS mcv_not_stats;
+CREATE STATISTICS mcv_not_stats (mcv) ON (nullif(a, true)), b FROM mcv_not_test;
+ANALYZE mcv_not_test;
+SELECT * FROM check_estimated_rows('SELECT * FROM mcv_not_test WHERE NOT nullif(a, true) AND b = 1');
+DROP TABLE mcv_not_test;
+
+-- NOT must use the number of distinct values when grouping removes MCVs.
+CREATE TABLE not_grouped_test (a boolean, b integer) WITH (autovacuum_enabled = off);
+INSERT INTO not_grouped_test SELECT true, i FROM generate_series(1, 10000) AS g(i);
+ANALYZE not_grouped_test;
+SELECT * FROM check_estimated_rows('WITH s AS MATERIALIZED (SELECT DISTINCT a, b FROM not_grouped_test) SELECT * FROM s WHERE NOT a');
+DROP TABLE not_grouped_test;
+
+-- Boolean tests of NOT must preserve the three-valued logic of NULL.
+CREATE TABLE not_bool_test (id integer, deleted boolean) WITH (autovacuum_enabled = off);
+INSERT INTO not_bool_test
+SELECT i, CASE WHEN i <= 9500 THEN NULL WHEN i <= 9900 THEN true ELSE false END
+FROM generate_series(1, 10000) AS g(i);
+ANALYZE not_bool_test;
+SELECT * FROM check_estimated_rows('SELECT * FROM not_bool_test WHERE NOT deleted');
+CREATE VIEW not_bool_view AS SELECT id, NOT deleted AS active FROM not_bool_test;
+SELECT * FROM check_estimated_rows('SELECT * FROM not_bool_view WHERE active IS TRUE');
+SELECT * FROM check_estimated_rows('SELECT * FROM not_bool_view WHERE active IS NOT TRUE');
+SELECT * FROM check_estimated_rows('SELECT * FROM not_bool_view WHERE active IS FALSE');
+SELECT * FROM check_estimated_rows('SELECT * FROM not_bool_view WHERE active IS NOT FALSE');
+SELECT * FROM check_estimated_rows('SELECT * FROM not_bool_view WHERE active IS UNKNOWN');
+SELECT * FROM check_estimated_rows('SELECT * FROM not_bool_view WHERE active IS NOT UNKNOWN');
+DROP VIEW not_bool_view;
+DROP TABLE not_bool_test;
+
 CREATE TABLE mcv_lists (
     filler1 TEXT,
     filler2 NUMERIC,
-- 
2.34.1

Reply via email to