Re: Propagate stadistinct through GROUP BY/DISTINCT in subqueries and CTEs

From: Richard Guo <guofenglinux(at)gmail(dot)com>
To: Pg Hackers <pgsql-hackers(at)lists(dot)postgresql(dot)org>
Subject: Re: Propagate stadistinct through GROUP BY/DISTINCT in subqueries and CTEs
Date: 2026-07-07 05:31:46
Message-ID: CAMbWs49G9U+QWMDhU9sSLQQyq1i=grQXReXLk5Zg5WTPmqACRw@mail.gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

On Mon, Apr 13, 2026 at 10:18 AM Richard Guo <guofenglinux(at)gmail(dot)com> wrote:
> For DISTINCT or GROUP BY key columns that are simple Vars, I think we
> can propagate stadistinct from the base table, because the set of
> distinct values is preserved after grouping. MCV frequencies,
> histograms, and correlation data are not valid since GROUP BY and
> DISTINCT change the frequency distribution, but with stadistinct
> alone, callers like var_eq_const() can use a 1/ndistinct estimate
> rather than 1/DEFAULT_NUM_DISTINCT.
>
> Attached is a patch to do this.

Upon self-review, I realized that stanullfrac wasn't adjusted. Since
grouping collapses NULL values, we should account for that here.

Attached is v2 addressing this. For a single grouping key, at most
one NULL group remains, so we set it to 1 / (ndistinct + 1). With
multiple grouping keys, the surviving NULL count is underdetermined,
so we approximate it as zero; NULLs collapse far more aggressively
than non-NULLs, so the real fraction is well below the base table's,
and erring low keeps estimates on the hash-join-favoring side.

- Richard

Attachment Content-Type Size
v2-0001-Propagate-stadistinct-through-GROUP-BY-DISTINCT-i.patch application/octet-stream 14.4 KB

In response to

Browse pgsql-hackers by date

  From Date Subject
Next Message Andrey Rachitskiy 2026-07-07 05:44:45 Re: [PATCH] Limit PL/Perl scalar copies to work_mem
Previous Message Henson Choi 2026-07-07 04:08:42 Re: Row pattern recognition