Re: Can any_value be used like first_value in an aggregate? - Mailing list pgsql-general

From Tom Lane
Subject Re: Can any_value be used like first_value in an aggregate?
Date
Msg-id 1337453.1719335325@sss.pgh.pa.us
Whole thread Raw
In response to Can any_value be used like first_value in an aggregate?  (Bruno Wolff III <bruno@wolff.to>)
Responses Re: Can any_value be used like first_value in an aggregate?
List pgsql-general
Bruno Wolff III <bruno@wolff.to> writes:
> For example, is output of 10 guaranteed in the following:
> bruno=> select any_value(x order by x desc) from generate_series(1,10) as x;
>  any_value 
> -----------
>         10
> (1 row)

Not really.  It will work that way in simple cases, but I think the
behavior stops being predictable if the input gets large enough to
induce the planner to use parallel aggregation.  In any case, the
example shown isn't amazingly efficient since it'll still perform
a sort to meet the ORDER BY spec.

> The use case is that I want to return a value of one column that is paired 
> with the maximum value of another column in each group when using GROUP BY.

Use window functions (i.e. first_value).  This is what they're for,
and they are smart enough to do just one sort for functions sharing
a common window spec.

            regards, tom lane



pgsql-general by date:

Previous
From: Bruno Wolff III
Date:
Subject: Can any_value be used like first_value in an aggregate?
Next
From: Yongye Serkfem
Date:
Subject: Replication After manual Failover