Re: Preserve presorted ORDER BY keys when reordering DISTINCT ON keys

From: Andrei Lepikhov <lepihov(at)gmail(dot)com>
To: Tender Wang <tndrwang(at)gmail(dot)com>, Chengpeng Yan <chengpeng_yan(at)outlook(dot)com>
Cc: PostgreSQL Hackers <pgsql-hackers(at)lists(dot)postgresql(dot)org>
Subject: Re: Preserve presorted ORDER BY keys when reordering DISTINCT ON keys
Date: 2026-11-29 13:23:21
Message-ID: fc0a0db6-c95c-42d8-8fc9-1c34e872182f@gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

On 29/11/2026 02:56, Tender Wang wrote:
> Hi,
>
> Chengpeng Yan <chengpeng_yan(at)outlook(dot)com> 于2026年11月25日周三 21:09写道:
>> Thanks for working on this. I reviewed v1 and it looks good to me. I
>> wonder if it's worth adding a negative test with an index on (x, y, w
>> DESC, z DESC) and a query with ORDER BY y, x, z DESC, w DESC. If the
>> plan uses that index, it should still sort before Unique to pick the
>> right row.

The feature looks promising.

This patch adds to the search scope the possibility of performing a UNIQUE
operation before the sort, which is good for a couple of reasons:
1. UNIQUE will probably remove some fraction of duplicated rows.
2. Top-N bounded sort may be applied more frequently.

So, let's discuss regressions. At first glance, executor-side regression looks
well-contained. I can imagine only one case: when Unique -> Sort -> SeqScan is
still effective, but the patched version already picks Sort -> Unique -> Index
Scan because of a cost misestimation.

But with planning-time regressions, it might be more difficult to identify a
specific case. For example, in [1], a trivial optimisation that added one more
sort to pathlist caused huge planning overhead (more than 100x in production
with 100+ joins), which forced me to limit its scope.

So, after reviewing this feature, I found no non-linear growth in planning
effort for now. But it might still add ~40% growth in memory and planning time
(see repro in the attachment). It may be important, because the feature itself
covers a quite rare case. Am I wrong?

[1]
https://www.postgresql.org/message-id/67352ee9-fada-4253-a73d-d0f101dfb424@gmail.com

--
regards, Andrei Lepikhov,
pgEdge

Attachment Content-Type Size
rr1.sql text/plain 1.6 KB

In response to

Browse pgsql-hackers by date

  From Date Subject
Next Message Raja Sai pranav 2026-11-29 14:00:59 Re: Fix empty and whitespace-only input handling in option_parse_int()
Previous Message Jelte Fennema-Nio 2026-11-29 10:55:23 Re: Safer and simpler HTAB macros (foreach_hash and hash_make), take two