While looking into extended statistics, I found a similar issue in mcv_get_match_bitmap().

For a NOT clause, the function builds a match bitmap for its argument and then inverts it. However, the bitmap does not distinguish FALSE from NULL. As a result, for NOT applied to a nullable Boolean column, MCV items containing NULL are treated as matches.

Example:

```
CREATE TABLE t (a boolean, b integer);
INSERT INTO t
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) ON a, b FROM t;
ANALYZE t;

-- before v2 patch
EXPLAIN ANALYZE SELECT * FROM t WHERE NOT a AND b = 1;
                                            QUERY PLAN
---------------------------------------------------------------------------------------------------
 Seq Scan on t  (cost=0.00..17.50 *rows=320* width=5) (actual time=0.131..0.193 *rows=400.00* loops=1)
   Filter: ((NOT a) AND (b = 1))
   Rows Removed by Filter: 600
   Buffers: shared hit=9 dirtied=1 written=1
 Planning:
   Buffers: shared hit=12
 Planning Time: 0.102 ms
 Execution Time: 0.214 ms
(8 rows)

EXPLAIN ANALYZE SELECT * FROM t WHERE NOT a OR b = 1;
                                            QUERY PLAN
---------------------------------------------------------------------------------------------------
 Seq Scan on t  (cost=0.00..17.50 *rows=880* width=5) (actual time=0.020..0.109 *rows=800.00* loops=1)
   Filter: ((NOT a) OR (b = 1))
   Rows Removed by Filter: 200
   Buffers: shared hit=5
 Planning Time: 0.079 ms
 Execution Time: 0.150 ms
(6 rows)

-- after v2 patch
EXPLAIN ANALYZE SELECT * FROM t WHERE NOT a AND b = 1;
                                            QUERY PLAN
---------------------------------------------------------------------------------------------------
 Seq Scan on t  (cost=0.00..17.50 *rows=400* width=5) (actual time=0.015..0.093 *rows=400.00* loops=1)
   Filter: ((NOT a) AND (b = 1))
   Rows Removed by Filter: 600
   Buffers: shared hit=5
 Planning:
   Buffers: shared hit=13
 Planning Time: 0.166 ms
 Execution Time: 0.121 ms
(8 rows)

EXPLAIN ANALYZE SELECT * FROM t WHERE NOT a OR b = 1;
                                            QUERY PLAN
---------------------------------------------------------------------------------------------------
 Seq Scan on t  (cost=0.00..17.50 *rows=800* width=5) (actual time=0.015..0.063 *rows=800.00* loops=1)
   Filter: ((NOT a) OR (b = 1))
   Rows Removed by Filter: 200
   Buffers: shared hit=5
 Planning Time: 0.080 ms
 Execution Time: 0.096 ms
(6 rows)
```

For the AND case, the MCV entry with a = NULL and b = 1 is incorrectly counted as matching NOT a. For the OR case, the incorrect match bitmap also affects the estimated overlap between the conditions.

I have tried handling NOT over a bare Boolean column or expression by checking the MCV value directly: it matches only when the value is non-NULL and FALSE.

--
Best regards,
Ilia Evdokimov,
Tantor Labs LLC,
https://tantorlabs.com/
From 0395b8d2247009bf8f19c6725dd417861dc0bf21 Mon Sep 17 00:00:00 2001
From: Ilia Evdokimov <[email protected]>
Date: Thu, 3 Dec 2026 16:54:48 +0300
Subject: [PATCH v2] Fix NOT selectivity estimates for nullable boolean
 expressions

When statistics are available for the argument of NOT, use
booltestsel(IS_FALSE) to exclude NULL values from the selectivity
estimate. Otherwise, retain the existing recursive estimate.

Fix the corresponding issue in multivariate MCV selectivity estimates.
Inverting the match bitmap for a boolean column or expression also
matches NULL values, so check MCV values directly for FALSE instead.
---
 src/backend/optimizer/path/clausesel.c  | 26 +++++++++++++++------
 src/backend/statistics/mcv.c            | 25 +++++++++++++++++++++
 src/test/regress/expected/stats_ext.out | 30 +++++++++++++++++++++++++
 src/test/regress/sql/stats_ext.sql      | 16 +++++++++++++
 4 files changed, 90 insertions(+), 7 deletions(-)

diff --git a/src/backend/optimizer/path/clausesel.c b/src/backend/optimizer/path/clausesel.c
index c22cbfc9ca0..4b72ec61981 100644
--- a/src/backend/optimizer/path/clausesel.c
+++ b/src/backend/optimizer/path/clausesel.c
@@ -803,13 +803,25 @@ 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 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);
 	}
 	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/test/regress/expected/stats_ext.out b/src/test/regress/expected/stats_ext.out
index decdca0c161..3f22ef5b93a 100644
--- a/src/test/regress/expected/stats_ext.out
+++ b/src/test/regress/expected/stats_ext.out
@@ -1944,6 +1944,36 @@ 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;
 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..61e62b1dc75 100644
--- a/src/test/regress/sql/stats_ext.sql
+++ b/src/test/regress/sql/stats_ext.sql
@@ -960,6 +960,22 @@ 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;
+
 CREATE TABLE mcv_lists (
     filler1 TEXT,
     filler2 NUMERIC,
-- 
2.34.1

Reply via email to