| From: | Chengpeng Yan <chengpeng_yan(at)outlook(dot)com> |
|---|---|
| To: | Tomas Vondra <tomas(at)vondra(dot)me> |
| Cc: | Pavel Stehule <pavel(dot)stehule(at)gmail(dot)com>, PostgreSQL Hackers <pgsql-hackers(at)lists(dot)postgresql(dot)org> |
| Subject: | Re: extremely slow planner when DISTINCT clause holds more columns |
| Date: | 2026-12-06 04:38:01 |
| Message-ID: | 05D6668D-588E-433F-847B-34FEDE3E7C3B@outlook.com |
| Views: | Whole Thread | Raw Message | Download mbox | Resend email |
| Thread: | |
| Lists: | pgsql-hackers |
Hi,
> On Dec 6, 2026, at 08:55, Tomas Vondra <tomas(at)vondra(dot)me> wrote:
>
> On 12/5/26 22:57, Tomas Vondra wrote:
>>
>> ...
>>
>> I haven't tried, but I think the key to improving this is to get rid of
>> the linear search, likely by replacing it with a lookup in a hash table,
>> or something like that.
>>
>> ISTM that if we extracted info about the EC for the "var" expression
>> (I'm assuming there can be just one, but maybe we'd need to keep a
>> list?), and keep a hash of those. And use that to quickly find if
>> there's a matching expression, without the linear search.
>>
>> It'd need to be a bit more elaborate, because we only eliminate
>> expressions from different relations, so we'd need to keep a list of
>> rels for each EC, probably.
>>
>
> I meant something like the attached patch. It's a dirty PoC patch, it
> passes "make check" but it can be broken in some way. I've also not
> checked if it doesn't hurt simple queries etc.
>
>
> --
> Tomas Vondra
> <add_unique_group_var.patch>
I agree with your analysis: the cost is the linear search in
add_unique_group_var(), where each pair of grouping Vars from
different relations calls exprs_known_equal(), which walks all of
root->eq_classes. The O(N^2) pairs you mention each walk roughly N
ECs, so it is about O(N^3) equal() calls.
Your PoC fixes this, but it restructures the function quite a bit.
I wonder if a smaller change would be enough: look up the ECs of each
grouping expression once, keep them in its GroupVarInfo, and then just
check whether two Vars share an EC instead of calling
exprs_known_equal(). The EC lookups then cost O(N * M), M being the
number of members of multi-member ECs, and the pairwise loop is O(N^2)
cheap comparisons.
Diff attached. Does that look workable to you?
--
Best regards,
Chengpeng Yan
| Attachment | Content-Type | Size |
|---|---|---|
| estimate_num_groups-ec-lookup.diff | application/octet-stream | 3.8 KB |
| From | Date | Subject | |
|---|---|---|---|
| Next Message | Raja Sai pranav | 2026-12-06 04:40:36 | Re: pg_receivewal doesn't truncate compressed WAL files on restart |
| Previous Message | Roberto Mello | 2026-12-06 02:48:12 | Re: Proposal: per-table row counts in pg_dump/pg_restore, with restore-time verification |