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