Re: [PATCH] Remove redundant ORDER BY from COUNT aggregates

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: John Naylor <johncnaylorls(at)gmail(dot)com>
Cc: Haibo Yan <tristan(dot)yim(at)gmail(dot)com>, PostgreSQL Hackers <pgsql-hackers(at)lists(dot)postgresql(dot)org>
Subject: Re: [PATCH] Remove redundant ORDER BY from COUNT aggregates
Date: 2026-08-12 14:46:52
Message-ID: 2640601.1786546012@sss.pgh.pa.us
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

John Naylor <johncnaylorls(at)gmail(dot)com> writes:
> On Wed, Aug 12, 2026 at 11:01 AM Haibo Yan <tristan(dot)yim(at)gmail(dot)com> wrote:
>> I’d like to propose a small optimization for aggregate-local ORDER BY in COUNT.
>> Currently, for example:
>>
>> SELECT count(a ORDER BY b) FROM t;
>>
>> is planned as an ordered aggregate, even though the ordering cannot affect the
>> result of COUNT. This may require a Sort, but the impact is broader than just
>> the extra sort: having aggorder also prevents partial aggregation and hash
>> aggregation, and prevents the aggregate from sharing state with an otherwise
>> identical count(a).

> The question that comes to mind is, why would someone (or a program
> for that matter) write it this way? Self-join elimination cited ORMs
> as a motivation, what is it for this case?

If someone did write that, they might have a good reason to. I don't
think we should expend planner cycles (not to mention development and
code maintenance effort) on looking for such cases.

regards, tom lane

In response to

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Matheus Alcantara 2026-08-12 14:49:21 Re: hashjoins vs. Bloom filters (yet again)
Previous Message Kevin Rocker 2026-08-12 14:46:25 Re: [PATCH] Fix vacuum_delay_point happening inside lock