Is PostgreSQL's any_value actually arbitrary when using ORDER BY?
The documentation states:
any_value ( anyelement ) → same as input type
Returns an arbitrary value from the non-null input values.
Example queries:
-- nonsensical
WITH vals (v) AS ( VALUES (1),(3),(4),(3),(2) )
SELECT any_value(v ORDER BY v = 3 DESC) FROM vals;
-- more realistic example
SELECT any_value(username ORDER BY user_id DESC) AS a_username FROM users;
I did see that version 17 documentation includes the following clause:
While all aggregates below accept an optional ORDER BY clause (as outlined in Section 4.2.7), the clause has only been added to aggregates whose output is affected by ordering.
But it doesn't mention whether any_value's output is affected by ordering.
Based on some trials, it appears to be deterministic.
(probably because any_value just returns the first not null value and respects the ORDER BY)
As a follow up question, if it's not arbitrary, would it be "bad" to rely on this behavior?