From c3865a1920a5e98e935327b51fbe6b496df692c4 Mon Sep 17 00:00:00 2001 From: Tender Wang Date: Fri, 4 Dec 2026 14:24:39 +0800 Subject: [PATCH] Account for all hash clauses in inner MCV estimation Multivariate ndistinct statistics provide a bucket size estimate but no most-common-value (MCV) frequency. final_cost_hashjoin() currently updates both estimates using only the hash clauses that were not covered by those statistics. If all clauses are covered, the inner MCV frequency retains its initial value of 1.0, which can incorrectly trigger the hash join memory penalty. Use all hash clauses to estimate the inner MCV frequency. Continue to use per-clause bucket size estimates only for clauses not covered by multivariate ndistinct statistics. --- src/backend/optimizer/path/costsize.c | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/backend/optimizer/path/costsize.c b/src/backend/optimizer/path/costsize.c index f760ef9aa3a..3d2f70be5bf 100644 --- a/src/backend/optimizer/path/costsize.c +++ b/src/backend/optimizer/path/costsize.c @@ -4527,8 +4527,11 @@ final_cost_hashjoin(PlannerInfo *root, HashPath *path, hashclauses, &innerbucketsize); - /* Pass through the remaining clauses */ - foreach(hcl, otherclauses) + /* + * Estimate the MCV frequency using all hash clauses. The extended + * ndistinct statistics above only estimate the bucket size. + */ + foreach(hcl, hashclauses) { RestrictInfo *restrictinfo = lfirst_node(RestrictInfo, hcl); Selectivity thisbucketsize; @@ -4578,7 +4581,9 @@ final_cost_hashjoin(PlannerInfo *root, HashPath *path, thismcvfreq = restrictinfo->left_mcvfreq; } - if (innerbucketsize > thisbucketsize) + /* Use the per-clause bucket size only for the remaining clauses. */ + if (innerbucketsize > thisbucketsize && + list_member_ptr(otherclauses, restrictinfo)) innerbucketsize = thisbucketsize; /* Disregard zero for MCV freq, it means we have no data */ if (thismcvfreq > 0.0 && innermcvfreq > thismcvfreq) -- 2.43.0