From 1c526c9472f147c318f61c6b21447941c853de46 Mon Sep 17 00:00:00 2001
From: Evdokimov Ilia <ilya.evdokimov@tantorlabs.com>
Date: Wed, 5 Aug 2026 10:20:35 +0300
Subject: [PATCH v1] Merge MCV match and sum loops in var_eq_cons

---
 src/backend/utils/adt/selfuncs.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/src/backend/utils/adt/selfuncs.c b/src/backend/utils/adt/selfuncs.c
index 2b4e6acf9a7..6213510d642 100644
--- a/src/backend/utils/adt/selfuncs.c
+++ b/src/backend/utils/adt/selfuncs.c
@@ -413,6 +413,7 @@ var_eq_const(VariableStatData *vardata, Oid oproid, Oid collation,
 		AttStatsSlot sslot;
 		bool		match = false;
 		int			i;
+		double		sumcommon = 0.0;
 
 		/*
 		 * Is the constant "=" to any of the column's most common values?
@@ -450,6 +451,8 @@ var_eq_const(VariableStatData *vardata, Oid oproid, Oid collation,
 			{
 				Datum		fresult;
 
+				sumcommon += sslot.numbers[i];
+
 				if (varonleft)
 					fcinfo->args[0].value = sslot.values[i];
 				else
@@ -484,11 +487,8 @@ var_eq_const(VariableStatData *vardata, Oid oproid, Oid collation,
 			 * of the common values.  Its selectivity cannot be more than
 			 * this:
 			 */
-			double		sumcommon = 0.0;
 			double		otherdistinct;
 
-			for (i = 0; i < sslot.nnumbers; i++)
-				sumcommon += sslot.numbers[i];
 			selec = 1.0 - sumcommon - nullfrac;
 			CLAMP_PROBABILITY(selec);
 
-- 
2.34.1

