Re: Document aggregate functions better w.r.t. ORDER BY - Mailing list pgsql-hackers

From David Rowley
Subject Re: Document aggregate functions better w.r.t. ORDER BY
Date
Msg-id CAApHDvpmQgWo8gqFmZ7Ot1cRazDiAKDBmQNJZTt7Waifo7htSw@mail.gmail.com
Whole thread Raw
In response to Re: Document aggregate functions better w.r.t. ORDER BY  ("David G. Johnston" <david.g.johnston@gmail.com>)
Responses Re: Document aggregate functions better w.r.t. ORDER BY
List pgsql-hackers
On Thu, 26 Oct 2023 at 13:10, David G. Johnston
<david.g.johnston@gmail.com> wrote:
> Question: Do you know whether we for certain always sort ascending here to compute the unique values or whether if,
say,there is an index on the column in descending order (or ascending and traversed backwards) that the data within the
aggregatecould, with an order by, be returned in descending order? 

The way it's currently coded, we seem to always require ascending
order.  See addTargetToGroupList().  The call to
get_sort_group_operators() only requests the ltOpr.

A quick test creating an index on a column with DESC shows that we end
up doing a backwards index scan so that we get the requested ascending
order:

create table b (b text);
create index on b (b desc);
explain select string_agg(distinct b,',') from b;
                                        QUERY PLAN
------------------------------------------------------------------------------------------
 Aggregate  (cost=67.95..67.97 rows=1 width=32)
   ->  Index Only Scan Backward using b_b_idx on b  (cost=0.15..64.55
rows=1360 width=32)
(2 rows)

However, I think we'd best stay clear of offering any guarantees in
the documents about this.  If we did that it would be much harder in
the future if we wanted to implement the DISTINCT aggregates by
hashing.

David



pgsql-hackers by date:

Previous
From: Michael Paquier
Date:
Subject: Re: Introduce a new view for checkpointer related stats
Next
From: Amit Langote
Date:
Subject: Re: remaining sql/json patches