are always just expressions and cannot be output-column names or numbers.
For example:
-SELECT array_agg(a ORDER BY b DESC) FROM table;
+WITH vals (v) AS ( VALUES (1),(3),(4),(3),(2) )
+SELECT array_agg(v ORDER BY v DESC) FROM vals;
+ array_agg
+-------------
+ {4,3,3,2,1}
+
+ Since jsonb only keeps the last matching key, ordering
+ of its keys can be significant:
+WITH vals (k, v) AS ( VALUES ('key0','1'), ('key1','3'), ('key1','2') )
+SELECT jsonb_object_agg(k, v ORDER BY v) FROM vals;
+ jsonb_object_agg
+----------------------------
+ {"key0": "1", "key1": "3"}
- If DISTINCT is specified in addition to an
- order_by_clause, then all the ORDER BY
- expressions must match regular arguments of the aggregate; that is,
- you cannot sort on an expression that is not included in the
- DISTINCT list.
+ If DISTINCT is specified with an
+ order_by_clause, ORDER
+ BY expressions can only reference columns in the
+ DISTINCT list. For example:
+WITH vals (v) AS ( VALUES (1),(3),(4),(3),(2) )
+SELECT array_agg(DISTINCT v ORDER BY v DESC) FROM vals;
+ array_agg
+-----------
+ {4,3,2,1}
+
-
- The ability to specify both DISTINCT and ORDER BY
- in an aggregate function is a
PostgreSQL extension.
-
-
-
Placing ORDER BY within the aggregate's regular argument
list, as described so far, is used when ordering the input rows for