Hash join costing can overestimate inner MCV frequency with extended statistics

From: Tender Wang <tndrwang(at)gmail(dot)com>
To: PostgreSQL Hackers <pgsql-hackers(at)lists(dot)postgresql(dot)org>
Subject: Hash join costing can overestimate inner MCV frequency with extended statistics
Date: 2026-12-04 06:58:22
Message-ID: CAHewXNkHt9zuLrLWL0yXtXn_Sj+YGXja2WgPdLihB+c8RiP=OQ@mail.gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Hi,

I found a hash join costing issue when multivariate ndistinct
statistics cover the hash clauses. I was testing this query with
parallel query disabled:

...
SELECT count(t2u.padding)
FROM t1u JOIN t2u
ON t1u.a = t2u.a AND t1u.b = t2u.b;
...

t1u has 1 million rows and t2u has 200,000 rows. With no extended
statistics, the planner chose a Merge Join with an estimated total
cost of about 184,000.
With merge join and nested loop disabled, the Hash Join built its hash
table on t2u and had an estimated total cost of about 852,000.
The Hash Join took about 1.68 s in my test, compared with 2.59 s for
the Merge Join. Both plans estimated about 1 million output rows,
close to the actual count.

Adding ndistinct statistics on t2u (a, b) improves the estimate of the
number of inner tuples examined per probe.
However, it also exposes a separate problem in final_cost_hashjoin().
When the extended statistics cover both hash clauses,
estimate_multivariate_bucketsize() returns an empty otherclauses list.
The loop that updates innermcvfreq then never runs, leaving it at 1.0.
Consequently, the skew memory check costs the path as if all 200,000
inner rows had the same join key. If that estimate exceeds the hash
memory limit,
the planner adds disable_cost to the Hash Join's startup cost. With
partial coverage, the same loop omits MCV frequencies for the covered
clauses.

The attached patch makes all hash clauses contribute to innermcvfreq
and uses otherclauses to determine which per-clause bucket size
estimates to apply.
This retains the benefit of the multivariate ndistinct estimate while
restoring the MCV inputs to the skew memory check.

--
Tender Wang

Attachment Content-Type Size
0001-Account-for-all-hash-clauses-in-inner-MCV-estimation.patch text/plain 2.1 KB
repro.sql application/octet-stream 1.3 KB

Browse pgsql-hackers by date

  From Date Subject
Previous Message cca5507 2026-12-04 06:54:49 Re: Remove useless memory context switch in ExecHashTableCreate()