From 898f7534f61bcdf0fd3aadc13155b81ef607ed13 Mon Sep 17 00:00:00 2001
From: zengxx <xiangxin_zeng@qq.com>
Date: Tue, 24 Nov 2026 18:20:23 +0800
Subject: [PATCH 1/1] Put presorted aggregate sort keys first in Aggregate
 input

With enable_presorted_aggregate, the input to an Aggregate node is
sorted by the grouping keys followed by the sort keys of the ordered
aggregates.  make_group_input_target() appended the Vars used by the
aggregates in expression-tree order, so the argument columns come before
the key columns, e.g. (g, v, k) for

    SELECT g, string_agg(v, ',' ORDER BY k) FROM t GROUP BY g

with a text column v.

tuplesort caches only the first sort key.  Every other key is fetched
from the tuple during each comparison that ties on the earlier keys.
When a varlena argument column sits in front of such a key, its length
header has to be read first, every time.  make_window_input_target()
already puts the window keys first; do the same for grouping.

Put the Vars used in the sort keys of presorted aggregates into the
input target ahead of the remaining non-group Vars.  Only presorted
aggregates are considered: the others sort their own input inside the
Aggregate node, on tuples built from their own argument list, so moving
their keys in the input buys nothing; and a varlena key of a losing
aggregate would end up in front of the real sort keys.  The keys are
taken in sort order (aggdistinct, else aggorder), which is the same list
the executor sorts an aggregate by.

Skip this when it cannot matter, so that plans stay the same for queries
that gain nothing: when no aggregate sort key was appended to the
grouping keys, or when there is a single sort key, which tuplesort
fetches once per tuple wherever it is.

A query that benefits may get one more projection (Result or Subquery
Scan) when its relation is a non-partitioned appendrel or a subquery,
because those do not regenerate their paths for the new target.  The
projection also adds to the estimated cost, which can tip a close
serial/parallel choice toward a parallel plan.  It is cheap: over a 1.2
million-row inheritance table with fixed-width columns, where nothing is
gained, the query took 710 ms instead of 690 ms (5 rounds).

On a table of 2 million rows with 10 groups and a text column v, with a
serial plan and the sort in memory, the query above takes 1051 ms
instead of 1554 ms (6 rounds of 10 runs each).  Plans and results of
queries outside the condition are unchanged.  Regression tests pin the
column order for 26 plans; five of the queries are run as well.
---
 src/backend/optimizer/plan/planner.c     | 113 +++++
 src/test/regress/expected/aggregates.out | 534 +++++++++++++++++++++++
 src/test/regress/sql/aggregates.sql      | 184 ++++++++
 3 files changed, 831 insertions(+)

diff --git a/src/backend/optimizer/plan/planner.c b/src/backend/optimizer/plan/planner.c
index 568a1b2a34..20aaaa9807 100644
--- a/src/backend/optimizer/plan/planner.c
+++ b/src/backend/optimizer/plan/planner.c
@@ -5814,6 +5814,85 @@ create_ordered_paths(PlannerInfo *root,
 	return ordered_rel;
 }
 
+/*
+ * collect_agg_key_vars_walker
+ *		Expression-tree walker callback to collect the Vars used in the
+ *		ORDER BY / DISTINCT key expressions of presorted aggregates.
+ *
+ * adjust_group_pathkeys_for_groupagg() arranges for the aggregation input
+ * to be sorted by the ORDER BY / DISTINCT keys of the aggregates it has
+ * marked aggpresorted.  Here we collect the Vars used in those key
+ * expressions, in key order, so that make_group_input_target can place them
+ * in the aggregation input target before the plain argument Vars.
+ *
+ * Aggregates that are not presorted sort their own input inside the
+ * Aggregate node.  Their keys are not sort keys of the Aggregate's input, so
+ * moving their columns would only reshuffle the arguments of the other
+ * aggregates; we leave them alone.
+ *
+ * Putting the sort key columns in front of the payload columns matches the
+ * convention make_window_input_target uses for window PARTITION BY / ORDER
+ * BY clauses:  when the aggregation input needs an explicit Sort, the
+ * tuples fed to the Sort then have the sort keys in front of the argument
+ * columns.  tuplesort caches only the first sort key in SortTuple.datum1,
+ * so comparisons of any later key must fetch that column afresh via
+ * heap_getattr; that fetch is much cheaper when it does not have to step
+ * over variable-width argument columns to locate the key (offsets beyond
+ * the first variable-width column cannot be cached).
+ *
+ * We recurse into the whole expression tree, so that Aggrefs nested inside
+ * other expression types, e.g. WindowFunc arguments, are handled too.  The
+ * pull_var_clause flags used here must match the ones used for
+ * non_group_vars in make_group_input_target, so that the equal()-based
+ * de-duplication in add_new_columns_to_pathtarget works.
+ */
+static bool
+collect_agg_key_vars_walker(Node *node, void *context)
+{
+	List	  **vars = context;
+
+	if (node == NULL)
+		return false;
+
+	if (IsA(node, Aggref))
+	{
+		Aggref	   *aggref = (Aggref *) node;
+
+		if (aggref->aggpresorted)
+		{
+			/*
+			 * The keys are taken in sort order, not in Aggref->args order:
+			 * the parser lets an ORDER BY item that equals an argument reuse
+			 * the argument's TargetEntry (see transformAggregateCall), so a
+			 * plain argument may come first in args while being a later sort
+			 * key.  When there is a DISTINCT clause, the ORDER BY keys are a
+			 * prefix of the DISTINCT keys (see transformDistinctClause) and
+			 * it is the latter the input is sorted by.  This is the same
+			 * sort list adjust_group_pathkeys_for_groupagg() uses, and
+			 * the one build_pertrans_for_aggref() would sort by.
+			 */
+			List	   *sortlist = aggref->aggdistinct ?
+											aggref->aggdistinct : aggref->aggorder;
+			ListCell   *lc;
+
+			foreach(lc, sortlist)
+			{
+				SortGroupClause *sortcl = lfirst_node(SortGroupClause, lc);
+				TargetEntry *tle = get_sortgroupclause_tle(sortcl,
+														   aggref->args);
+
+				*vars = list_concat(*vars,
+									pull_var_clause((Node *) tle->expr,
+													PVC_RECURSE_AGGREGATES |
+													PVC_RECURSE_WINDOWFUNCS |
+													PVC_INCLUDE_PLACEHOLDERS));
+			}
+		}
+	}
+
+	return expression_tree_walker(node, collect_agg_key_vars_walker,
+								  context);
+}
 
 /*
  * make_group_input_target
@@ -5836,6 +5915,9 @@ create_ordered_paths(PlannerInfo *root,
  *		a+b,c,d
  * where the a+b target will be used by the Sort/Group steps, and the
  * other targets will be used for computing the final results.
+ * If ordered aggregates make the subplan sort by keys beyond the GROUP
+ * BY ones, the Vars in those keys are placed right after the GROUP BY
+ * items and ahead of the remaining Vars (see the comment in the body).
  *
  * 'final_target' is the query's final target list (in PathTarget form)
  *
@@ -5928,6 +6010,37 @@ make_group_input_target(PlannerInfo *root, PathTarget *final_target)
 								  bms_make_singleton(root->group_rtindex),
 								  NULL);
 	}
+
+	/*
+	 * Put the Vars used in the sort keys of presorted aggregates into the
+	 * input target before the remaining non-group Vars, so that any Sort
+	 * below the grouping step sees the sort keys in front of the argument
+	 * columns (see collect_agg_key_vars_walker).
+	 *
+	 * Only do that when it can matter.  adjust_group_pathkeys_for_groupagg()
+	 * appends the keys of presorted aggregates to root->group_pathkeys, after
+	 * the plain GROUP BY keys; a key column can be something other than the
+	 * first sort key only when such keys were appended and there is more
+	 * than one sort key in total.  (tuplesort fetches the first sort key
+	 * only once per tuple, so the position of a lone sort key does not
+	 * matter.)  The first test is the same one gather_grouping_paths() uses
+	 * to detect the extra keys.  When it fails, every sort key is a GROUP BY
+	 * column, and those already come before the argument columns, whether
+	 * or not some aggregate is presorted.  Nothing would be moved then, so
+	 * leave the input target alone.
+	 */
+	if (list_length(root->group_pathkeys) > root->num_groupby_pathkeys &&
+		list_length(root->group_pathkeys) > 1)
+	{
+		List	   *agg_key_vars = NIL;
+
+		(void) expression_tree_walker((Node *) non_group_cols,
+									  collect_agg_key_vars_walker,
+									  &agg_key_vars);
+		add_new_columns_to_pathtarget(input_target, agg_key_vars);
+		list_free(agg_key_vars);
+	}
+
 	add_new_columns_to_pathtarget(input_target, non_group_vars);
 
 	/* clean up cruft */
diff --git a/src/test/regress/expected/aggregates.out b/src/test/regress/expected/aggregates.out
index 275263c293..5e8ec1dc82 100644
--- a/src/test/regress/expected/aggregates.out
+++ b/src/test/regress/expected/aggregates.out
@@ -2073,6 +2073,540 @@ select sum(two order by two) from tenk1;
 (2 rows)
 
 reset enable_presorted_aggregate;
+-- Check that the sort key columns of presorted aggregates are placed ahead
+-- of the plain argument columns in the aggregation input.  tuplesort caches
+-- only the first sort key, so any other key is fetched from the tuple during
+-- comparisons, and that is cheaper when no variable-length column is in the
+-- way.  (make_window_input_target() uses the same convention for window
+-- PARTITION BY / ORDER BY keys.)
+explain (verbose, costs off)
+select ten, sum(unique1 order by two), max(unique1 order by two, four)
+from tenk1 group by ten;
+                                QUERY PLAN                                 
+---------------------------------------------------------------------------
+ GroupAggregate
+   Output: ten, sum(unique1 ORDER BY two), max(unique1 ORDER BY two, four)
+   Group Key: tenk1.ten
+   ->  Sort
+         Output: ten, two, four, unique1
+         Sort Key: tenk1.ten, tenk1.two, tenk1.four
+         ->  Seq Scan on public.tenk1
+               Output: ten, two, four, unique1
+(8 rows)
+
+-- Only the keys of aggregates that are presorted are moved.  The key of the
+-- second aggregate (four) does not match the sort order chosen for the first
+-- aggregate, so the second one sorts its own input inside the Aggregate node
+-- and its key column stays where the target list has it.
+explain (verbose, costs off)
+select ten, sum(unique1 order by two), array_agg(unique2 order by four)
+from tenk1 group by ten;
+                                 QUERY PLAN                                 
+----------------------------------------------------------------------------
+ GroupAggregate
+   Output: ten, sum(unique1 ORDER BY two), array_agg(unique2 ORDER BY four)
+   Group Key: tenk1.ten
+   ->  Sort
+         Output: ten, two, unique1, unique2, four
+         Sort Key: tenk1.ten, tenk1.two
+         ->  Seq Scan on public.tenk1
+               Output: ten, two, unique1, unique2, four
+(8 rows)
+
+-- The key columns are taken in sort order, not in Aggref->args order.
+explain (verbose, costs off)
+select ten, sum(unique1 order by two, unique1) from tenk1 group by ten;
+                      QUERY PLAN                       
+-------------------------------------------------------
+ GroupAggregate
+   Output: ten, sum(unique1 ORDER BY two, unique1)
+   Group Key: tenk1.ten
+   ->  Sort
+         Output: ten, two, unique1
+         Sort Key: tenk1.ten, tenk1.two, tenk1.unique1
+         ->  Seq Scan on public.tenk1
+               Output: ten, two, unique1
+(8 rows)
+
+-- Without GROUP BY the aggregate keys are the only sort keys.
+explain (verbose, costs off)
+select sum(unique1 order by ten, two) from tenk1;
+                QUERY PLAN                
+------------------------------------------
+ Aggregate
+   Output: sum(unique1 ORDER BY ten, two)
+   ->  Sort
+         Output: ten, two, unique1
+         Sort Key: tenk1.ten, tenk1.two
+         ->  Seq Scan on public.tenk1
+               Output: ten, two, unique1
+(7 rows)
+
+-- A single sort key is fetched once per tuple, so its column is not moved.
+explain (verbose, costs off)
+select sum(unique1 order by two) from tenk1;
+              QUERY PLAN              
+--------------------------------------
+ Aggregate
+   Output: sum(unique1 ORDER BY two)
+   ->  Sort
+         Output: unique1, two
+         Sort Key: tenk1.two
+         ->  Seq Scan on public.tenk1
+               Output: unique1, two
+(7 rows)
+
+-- Nothing is moved when presorted aggregates are disabled.
+set enable_presorted_aggregate to off;
+explain (verbose, costs off)
+select ten, sum(unique1 order by two) from tenk1 group by ten;
+                QUERY PLAN                
+------------------------------------------
+ GroupAggregate
+   Output: ten, sum(unique1 ORDER BY two)
+   Group Key: tenk1.ten
+   ->  Sort
+         Output: ten, unique1, two
+         Sort Key: tenk1.ten
+         ->  Seq Scan on public.tenk1
+               Output: ten, unique1, two
+(8 rows)
+
+reset enable_presorted_aggregate;
+-- A DISTINCT aggregate is sorted by its whole DISTINCT list:  the ORDER BY
+-- keys first, then the remaining arguments.
+explain (verbose, costs off)
+select ten, max(unique1), jsonb_object_agg(distinct two, four order by four)
+from tenk1 group by ten;
+                                   QUERY PLAN                                    
+---------------------------------------------------------------------------------
+ GroupAggregate
+   Output: ten, max(unique1), jsonb_object_agg(DISTINCT two, four ORDER BY four)
+   Group Key: tenk1.ten
+   ->  Sort
+         Output: ten, four, two, unique1
+         Sort Key: tenk1.ten, tenk1.four, tenk1.two
+         ->  Seq Scan on public.tenk1
+               Output: ten, four, two, unique1
+(8 rows)
+
+-- A sort key that is also a GROUP BY column is not added a second time.
+explain (verbose, costs off)
+select ten, sum(unique1 order by ten, two) from tenk1 group by ten;
+                  QUERY PLAN                   
+-----------------------------------------------
+ GroupAggregate
+   Output: ten, sum(unique1 ORDER BY ten, two)
+   Group Key: tenk1.ten
+   ->  Sort
+         Output: ten, two, unique1
+         Sort Key: tenk1.ten, tenk1.two
+         ->  Seq Scan on public.tenk1
+               Output: ten, two, unique1
+(8 rows)
+
+-- A variable-length argument column is what the reordering is for.  tenk1
+-- has none, so cast one to numeric in a CTE that is not inlined.
+explain (verbose, costs off)
+with t as materialized (select ten, unique1::numeric as v, two, four from tenk1)
+select ten, sum(v order by two, four) from t group by ten;
+                                  QUERY PLAN                                  
+------------------------------------------------------------------------------
+ GroupAggregate
+   Output: t.ten, sum(t.v ORDER BY t.two, t.four)
+   Group Key: t.ten
+   CTE t
+     ->  Seq Scan on public.tenk1
+           Output: tenk1.ten, (tenk1.unique1)::numeric, tenk1.two, tenk1.four
+   ->  Sort
+         Output: t.ten, t.two, t.four, t.v
+         Sort Key: t.ten, t.two, t.four
+         ->  CTE Scan on t
+               Output: t.ten, t.two, t.four, t.v
+(11 rows)
+
+-- An ordered aggregate that appears only in the HAVING clause.
+explain (verbose, costs off)
+select ten from tenk1 group by ten having sum(unique1 order by two, four) > 0;
+                            QUERY PLAN                             
+-------------------------------------------------------------------
+ GroupAggregate
+   Output: ten
+   Group Key: tenk1.ten
+   Filter: (sum(tenk1.unique1 ORDER BY tenk1.two, tenk1.four) > 0)
+   ->  Sort
+         Output: ten, two, four, unique1
+         Sort Key: tenk1.ten, tenk1.two, tenk1.four
+         ->  Seq Scan on public.tenk1
+               Output: ten, two, four, unique1
+(9 rows)
+
+-- An ordered aggregate in the ORDER BY clause of a window function.
+explain (verbose, costs off)
+select ten, rank() over (order by sum(unique1 order by two, four))
+from tenk1 group by ten;
+                                               QUERY PLAN                                                
+---------------------------------------------------------------------------------------------------------
+ WindowAgg
+   Output: ten, rank() OVER w1, (sum(unique1 ORDER BY two, four))
+   Window: w1 AS (ORDER BY (sum(tenk1.unique1 ORDER BY tenk1.two, tenk1.four)) ROWS UNBOUNDED PRECEDING)
+   ->  Sort
+         Output: ten, (sum(unique1 ORDER BY two, four))
+         Sort Key: (sum(tenk1.unique1 ORDER BY tenk1.two, tenk1.four))
+         ->  GroupAggregate
+               Output: ten, sum(unique1 ORDER BY two, four)
+               Group Key: tenk1.ten
+               ->  Sort
+                     Output: ten, two, four, unique1
+                     Sort Key: tenk1.ten, tenk1.two, tenk1.four
+                     ->  Seq Scan on public.tenk1
+                           Output: ten, two, four, unique1
+(14 rows)
+
+-- The Vars inside an expression sort key are moved as well.  The expression
+-- itself is added by the Sort, at the end of the row.
+explain (verbose, costs off)
+select ten, sum(unique1 order by two + four) from tenk1 group by ten;
+                         QUERY PLAN                          
+-------------------------------------------------------------
+ GroupAggregate
+   Output: ten, sum(unique1 ORDER BY ((two + four)))
+   Group Key: tenk1.ten
+   ->  Sort
+         Output: ten, two, four, unique1, ((two + four))
+         Sort Key: tenk1.ten, ((tenk1.two + tenk1.four))
+         ->  Seq Scan on public.tenk1
+               Output: ten, two, four, unique1, (two + four)
+(8 rows)
+
+-- The aggregate is found when it is nested inside a larger expression.
+explain (verbose, costs off)
+select ten, sum(unique1 order by two, four) + 1 from tenk1 group by ten;
+                      QUERY PLAN                      
+------------------------------------------------------
+ GroupAggregate
+   Output: ten, (sum(unique1 ORDER BY two, four) + 1)
+   Group Key: tenk1.ten
+   ->  Sort
+         Output: ten, two, four, unique1
+         Sort Key: tenk1.ten, tenk1.two, tenk1.four
+         ->  Seq Scan on public.tenk1
+               Output: ten, two, four, unique1
+(8 rows)
+
+-- GROUP BY columns come first, each of them once, then the aggregate keys.
+explain (verbose, costs off)
+select ten, two, sum(unique1 order by two, four) from tenk1 group by ten, two;
+                     QUERY PLAN                      
+-----------------------------------------------------
+ GroupAggregate
+   Output: ten, two, sum(unique1 ORDER BY two, four)
+   Group Key: tenk1.ten, tenk1.two
+   ->  Sort
+         Output: ten, two, four, unique1
+         Sort Key: tenk1.ten, tenk1.two, tenk1.four
+         ->  Seq Scan on public.tenk1
+               Output: ten, two, four, unique1
+(8 rows)
+
+-- A GROUP BY expression is kept as one column; the aggregate keys follow it.
+explain (verbose, costs off)
+select ten + 1, sum(unique1 order by two, four) from tenk1 group by ten + 1;
+                         QUERY PLAN                         
+------------------------------------------------------------
+ GroupAggregate
+   Output: ((ten + 1)), sum(unique1 ORDER BY two, four)
+   Group Key: ((tenk1.ten + 1))
+   ->  Sort
+         Output: ((ten + 1)), two, four, unique1
+         Sort Key: ((tenk1.ten + 1)), tenk1.two, tenk1.four
+         ->  Seq Scan on public.tenk1
+               Output: (ten + 1), two, four, unique1
+(8 rows)
+
+-- A FILTER clause leaves an aggregate presorted when its arguments are plain
+-- Vars, so its keys are moved.  With an expression as argument the aggregate
+-- is not presorted, and nothing is moved.
+explain (verbose, costs off)
+select ten, sum(unique1 order by two, four) filter (where two > 0)
+from tenk1 group by ten;
+                               QUERY PLAN                                
+-------------------------------------------------------------------------
+ GroupAggregate
+   Output: ten, sum(unique1 ORDER BY two, four) FILTER (WHERE (two > 0))
+   Group Key: tenk1.ten
+   ->  Sort
+         Output: ten, two, four, unique1
+         Sort Key: tenk1.ten, tenk1.two, tenk1.four
+         ->  Seq Scan on public.tenk1
+               Output: ten, two, four, unique1
+(8 rows)
+
+explain (verbose, costs off)
+select ten, sum(unique1 + 1 order by two, four) filter (where two > 0)
+from tenk1 group by ten;
+                                  QUERY PLAN                                   
+-------------------------------------------------------------------------------
+ GroupAggregate
+   Output: ten, sum((unique1 + 1) ORDER BY two, four) FILTER (WHERE (two > 0))
+   Group Key: tenk1.ten
+   ->  Sort
+         Output: ten, unique1, two, four
+         Sort Key: tenk1.ten
+         ->  Seq Scan on public.tenk1
+               Output: ten, unique1, two, four
+(8 rows)
+
+-- A volatile function in the sort keys keeps an aggregate from being
+-- presorted.  Its key column (hundred) stays where the target list has it.
+explain (verbose, costs off)
+select ten, sum(unique1 order by two, four),
+       max(unique2 order by hundred, random())
+from tenk1 group by ten;
+                                        QUERY PLAN                                         
+-------------------------------------------------------------------------------------------
+ GroupAggregate
+   Output: ten, sum(unique1 ORDER BY two, four), max(unique2 ORDER BY hundred, (random()))
+   Group Key: tenk1.ten
+   ->  Sort
+         Output: ten, two, four, unique1, unique2, hundred
+         Sort Key: tenk1.ten, tenk1.two, tenk1.four
+         ->  Seq Scan on public.tenk1
+               Output: ten, two, four, unique1, unique2, hundred
+(8 rows)
+
+-- An ordered-set aggregate is never marked presorted and sorts its rows on
+-- its own.  The column it sorts by (four) stays behind the keys of the
+-- presorted aggregate.
+explain (verbose, costs off)
+select ten, percentile_cont(0.5) within group (order by four),
+       sum(unique1 order by two)
+from tenk1 group by ten;
+                                                              QUERY PLAN                                                               
+---------------------------------------------------------------------------------------------------------------------------------------
+ GroupAggregate
+   Output: ten, percentile_cont('0.5'::double precision) WITHIN GROUP (ORDER BY ((four)::double precision)), sum(unique1 ORDER BY two)
+   Group Key: tenk1.ten
+   ->  Sort
+         Output: ten, two, four, unique1
+         Sort Key: tenk1.ten, tenk1.two
+         ->  Seq Scan on public.tenk1
+               Output: ten, two, four, unique1
+(8 rows)
+
+-- Aggregate keys are not combined with the GROUP BY columns when there are
+-- grouping sets, so nothing is moved.
+explain (verbose, costs off)
+select ten, sum(unique1 order by two, four)
+from tenk1 group by grouping sets ((ten), ());
+                   QUERY PLAN                   
+------------------------------------------------
+ GroupAggregate
+   Output: ten, sum(unique1 ORDER BY two, four)
+   Group Key: tenk1.ten
+   Group Key: ()
+   ->  Sort
+         Output: ten, unique1, two, four
+         Sort Key: tenk1.ten
+         ->  Seq Scan on public.tenk1
+               Output: ten, unique1, two, four
+(9 rows)
+
+-- The keys also come first in the Sort below a Gather Merge.
+set parallel_setup_cost TO 0;
+set parallel_tuple_cost TO 0;
+set min_parallel_table_scan_size = 0;
+set max_parallel_workers_per_gather = 2;
+explain (verbose, costs off)
+select ten, sum(unique1 order by two, four) from tenk1 group by ten;
+                        QUERY PLAN                        
+----------------------------------------------------------
+ GroupAggregate
+   Output: ten, sum(unique1 ORDER BY two, four)
+   Group Key: tenk1.ten
+   ->  Gather Merge
+         Output: ten, two, four, unique1
+         Workers Planned: 2
+         ->  Sort
+               Output: ten, two, four, unique1
+               Sort Key: tenk1.ten, tenk1.two, tenk1.four
+               ->  Parallel Seq Scan on public.tenk1
+                     Output: ten, two, four, unique1
+(11 rows)
+
+reset max_parallel_workers_per_gather;
+reset min_parallel_table_scan_size;
+reset parallel_tuple_cost;
+reset parallel_setup_cost;
+-- The keys also come first in other plan shapes; some of them need an extra
+-- projection node for it.  These queries are run as well, since their
+-- results depend on the order the aggregates see.
+create temp table agg_key (g int, k int, v text);
+insert into agg_key values (1, 3, 'c'), (1, 1, 'a'), (1, 2, 'b'),
+                           (2, 2, 'b'), (2, 1, 'a');
+create temp table agg_key2 (g int, k int, v text);
+insert into agg_key2 values (0, 3, 'p'), (0, 1, 'q');
+analyze agg_key;
+analyze agg_key2;
+-- A subquery that is not pulled up produces its columns in the order it is
+-- written with, so a Subquery Scan is kept to bring the keys to the front.
+explain (verbose, costs off)
+select g, string_agg(v, ',' order by g, k)
+from (select g, v, k from agg_key offset 0) s group by g order by g;
+                         QUERY PLAN                          
+-------------------------------------------------------------
+ GroupAggregate
+   Output: s.g, string_agg(s.v, ','::text ORDER BY s.g, s.k)
+   Group Key: s.g
+   ->  Sort
+         Output: s.g, s.k, s.v
+         Sort Key: s.g, s.k
+         ->  Subquery Scan on s
+               Output: s.g, s.k, s.v
+               ->  Seq Scan on pg_temp.agg_key
+                     Output: agg_key.g, agg_key.v, agg_key.k
+(10 rows)
+
+select g, string_agg(v, ',' order by g, k)
+from (select g, v, k from agg_key offset 0) s group by g order by g;
+ g | string_agg 
+---+------------
+ 1 | a,b,c
+ 2 | a,b
+(2 rows)
+
+-- A sort key from the nullable side of an outer join.  Unmatched rows sort
+-- last, because ASC puts NULLs last.
+explain (verbose, costs off)
+select a.g, string_agg(a.v, ',' order by b.k, a.k)
+from agg_key a left join agg_key2 b on a.k = b.k
+group by a.g order by a.g;
+                         QUERY PLAN                          
+-------------------------------------------------------------
+ GroupAggregate
+   Output: a.g, string_agg(a.v, ','::text ORDER BY b.k, a.k)
+   Group Key: a.g
+   ->  Sort
+         Output: a.g, b.k, a.k, a.v
+         Sort Key: a.g, b.k, a.k
+         ->  Hash Left Join
+               Output: a.g, b.k, a.k, a.v
+               Hash Cond: (a.k = b.k)
+               ->  Seq Scan on pg_temp.agg_key a
+                     Output: a.g, a.k, a.v
+               ->  Hash
+                     Output: b.k
+                     ->  Seq Scan on pg_temp.agg_key2 b
+                           Output: b.k
+(15 rows)
+
+select a.g, string_agg(a.v, ',' order by b.k, a.k)
+from agg_key a left join agg_key2 b on a.k = b.k
+group by a.g order by a.g;
+ g | string_agg 
+---+------------
+ 1 | a,c,b
+ 2 | a,b
+(2 rows)
+
+-- An Append node cannot change the column order of its inputs, so a UNION
+-- ALL gets a Result node that brings the keys to the front.
+explain (verbose, costs off)
+select g, string_agg(v, ',' order by g, k)
+from (select g, k, v from agg_key union all select g, k, v from agg_key2) u
+group by g order by g;
+                                     QUERY PLAN                                      
+-------------------------------------------------------------------------------------
+ GroupAggregate
+   Output: agg_key.g, string_agg(agg_key.v, ','::text ORDER BY agg_key.g, agg_key.k)
+   Group Key: agg_key.g
+   ->  Sort
+         Output: agg_key.g, agg_key.k, agg_key.v
+         Sort Key: agg_key.g, agg_key.k
+         ->  Result
+               Output: agg_key.g, agg_key.k, agg_key.v
+               ->  Append
+                     ->  Seq Scan on pg_temp.agg_key
+                           Output: agg_key.g, agg_key.v, agg_key.k
+                     ->  Seq Scan on pg_temp.agg_key2
+                           Output: agg_key2.g, agg_key2.v, agg_key2.k
+(13 rows)
+
+select g, string_agg(v, ',' order by g, k)
+from (select g, k, v from agg_key union all select g, k, v from agg_key2) u
+group by g order by g;
+ g | string_agg 
+---+------------
+ 0 | q,p
+ 1 | a,b,c
+ 2 | a,b
+(3 rows)
+
+-- The same for an inheritance table.
+create temp table agg_key_child () inherits (agg_key);
+insert into agg_key_child values (1, 4, 'd'), (2, 3, 'c');
+analyze agg_key_child;
+explain (verbose, costs off)
+select g, string_agg(v, ',' order by g, k) from agg_key group by g order by g;
+                                     QUERY PLAN                                      
+-------------------------------------------------------------------------------------
+ GroupAggregate
+   Output: agg_key.g, string_agg(agg_key.v, ','::text ORDER BY agg_key.g, agg_key.k)
+   Group Key: agg_key.g
+   ->  Sort
+         Output: agg_key.g, agg_key.k, agg_key.v
+         Sort Key: agg_key.g, agg_key.k
+         ->  Result
+               Output: agg_key.g, agg_key.k, agg_key.v
+               ->  Append
+                     ->  Seq Scan on pg_temp.agg_key agg_key_1
+                           Output: agg_key_1.g, agg_key_1.v, agg_key_1.k
+                     ->  Seq Scan on pg_temp.agg_key_child agg_key_2
+                           Output: agg_key_2.g, agg_key_2.v, agg_key_2.k
+(13 rows)
+
+select g, string_agg(v, ',' order by g, k) from agg_key group by g order by g;
+ g | string_agg 
+---+------------
+ 1 | a,b,c,d
+ 2 | a,b,c
+(2 rows)
+
+-- For a partitioned table the scans are planned with the new order, so no
+-- Result node is needed.
+create temp table agg_part (g int, k int, v text) partition by list (g);
+create temp table agg_part1 partition of agg_part for values in (1);
+create temp table agg_part2 partition of agg_part for values in (2);
+insert into agg_part values (1, 3, 'c'), (1, 1, 'a'), (1, 2, 'b'),
+                            (2, 2, 'b'), (2, 1, 'a');
+explain (verbose, costs off)
+select g, string_agg(v, ',' order by g, k) from agg_part group by g order by g;
+                                       QUERY PLAN                                        
+-----------------------------------------------------------------------------------------
+ GroupAggregate
+   Output: agg_part.g, string_agg(agg_part.v, ','::text ORDER BY agg_part.g, agg_part.k)
+   Group Key: agg_part.g
+   ->  Sort
+         Output: agg_part.g, agg_part.k, agg_part.v
+         Sort Key: agg_part.g, agg_part.k
+         ->  Append
+               ->  Seq Scan on pg_temp.agg_part1 agg_part_1
+                     Output: agg_part_1.g, agg_part_1.k, agg_part_1.v
+               ->  Seq Scan on pg_temp.agg_part2 agg_part_2
+                     Output: agg_part_2.g, agg_part_2.k, agg_part_2.v
+(11 rows)
+
+select g, string_agg(v, ',' order by g, k) from agg_part group by g order by g;
+ g | string_agg 
+---+------------
+ 1 | a,b,c
+ 2 | a,b
+(2 rows)
+
+drop table agg_part;
+drop table agg_key_child;
+drop table agg_key2;
+drop table agg_key;
 --
 -- Test cases with FILTER clause
 --
diff --git a/src/test/regress/sql/aggregates.sql b/src/test/regress/sql/aggregates.sql
index 2bbb7668dd..cdc7004507 100644
--- a/src/test/regress/sql/aggregates.sql
+++ b/src/test/regress/sql/aggregates.sql
@@ -786,6 +786,190 @@ explain (costs off)
 select sum(two order by two) from tenk1;
 reset enable_presorted_aggregate;
 
+-- Check that the sort key columns of presorted aggregates are placed ahead
+-- of the plain argument columns in the aggregation input.  tuplesort caches
+-- only the first sort key, so any other key is fetched from the tuple during
+-- comparisons, and that is cheaper when no variable-length column is in the
+-- way.  (make_window_input_target() uses the same convention for window
+-- PARTITION BY / ORDER BY keys.)
+explain (verbose, costs off)
+select ten, sum(unique1 order by two), max(unique1 order by two, four)
+from tenk1 group by ten;
+
+-- Only the keys of aggregates that are presorted are moved.  The key of the
+-- second aggregate (four) does not match the sort order chosen for the first
+-- aggregate, so the second one sorts its own input inside the Aggregate node
+-- and its key column stays where the target list has it.
+explain (verbose, costs off)
+select ten, sum(unique1 order by two), array_agg(unique2 order by four)
+from tenk1 group by ten;
+
+-- The key columns are taken in sort order, not in Aggref->args order.
+explain (verbose, costs off)
+select ten, sum(unique1 order by two, unique1) from tenk1 group by ten;
+
+-- Without GROUP BY the aggregate keys are the only sort keys.
+explain (verbose, costs off)
+select sum(unique1 order by ten, two) from tenk1;
+
+-- A single sort key is fetched once per tuple, so its column is not moved.
+explain (verbose, costs off)
+select sum(unique1 order by two) from tenk1;
+
+-- Nothing is moved when presorted aggregates are disabled.
+set enable_presorted_aggregate to off;
+explain (verbose, costs off)
+select ten, sum(unique1 order by two) from tenk1 group by ten;
+reset enable_presorted_aggregate;
+
+-- A DISTINCT aggregate is sorted by its whole DISTINCT list:  the ORDER BY
+-- keys first, then the remaining arguments.
+explain (verbose, costs off)
+select ten, max(unique1), jsonb_object_agg(distinct two, four order by four)
+from tenk1 group by ten;
+
+-- A sort key that is also a GROUP BY column is not added a second time.
+explain (verbose, costs off)
+select ten, sum(unique1 order by ten, two) from tenk1 group by ten;
+
+-- A variable-length argument column is what the reordering is for.  tenk1
+-- has none, so cast one to numeric in a CTE that is not inlined.
+explain (verbose, costs off)
+with t as materialized (select ten, unique1::numeric as v, two, four from tenk1)
+select ten, sum(v order by two, four) from t group by ten;
+
+-- An ordered aggregate that appears only in the HAVING clause.
+explain (verbose, costs off)
+select ten from tenk1 group by ten having sum(unique1 order by two, four) > 0;
+
+-- An ordered aggregate in the ORDER BY clause of a window function.
+explain (verbose, costs off)
+select ten, rank() over (order by sum(unique1 order by two, four))
+from tenk1 group by ten;
+
+-- The Vars inside an expression sort key are moved as well.  The expression
+-- itself is added by the Sort, at the end of the row.
+explain (verbose, costs off)
+select ten, sum(unique1 order by two + four) from tenk1 group by ten;
+
+-- The aggregate is found when it is nested inside a larger expression.
+explain (verbose, costs off)
+select ten, sum(unique1 order by two, four) + 1 from tenk1 group by ten;
+
+-- GROUP BY columns come first, each of them once, then the aggregate keys.
+explain (verbose, costs off)
+select ten, two, sum(unique1 order by two, four) from tenk1 group by ten, two;
+
+-- A GROUP BY expression is kept as one column; the aggregate keys follow it.
+explain (verbose, costs off)
+select ten + 1, sum(unique1 order by two, four) from tenk1 group by ten + 1;
+
+-- A FILTER clause leaves an aggregate presorted when its arguments are plain
+-- Vars, so its keys are moved.  With an expression as argument the aggregate
+-- is not presorted, and nothing is moved.
+explain (verbose, costs off)
+select ten, sum(unique1 order by two, four) filter (where two > 0)
+from tenk1 group by ten;
+explain (verbose, costs off)
+select ten, sum(unique1 + 1 order by two, four) filter (where two > 0)
+from tenk1 group by ten;
+
+-- A volatile function in the sort keys keeps an aggregate from being
+-- presorted.  Its key column (hundred) stays where the target list has it.
+explain (verbose, costs off)
+select ten, sum(unique1 order by two, four),
+       max(unique2 order by hundred, random())
+from tenk1 group by ten;
+
+-- An ordered-set aggregate is never marked presorted and sorts its rows on
+-- its own.  The column it sorts by (four) stays behind the keys of the
+-- presorted aggregate.
+explain (verbose, costs off)
+select ten, percentile_cont(0.5) within group (order by four),
+       sum(unique1 order by two)
+from tenk1 group by ten;
+
+-- Aggregate keys are not combined with the GROUP BY columns when there are
+-- grouping sets, so nothing is moved.
+explain (verbose, costs off)
+select ten, sum(unique1 order by two, four)
+from tenk1 group by grouping sets ((ten), ());
+
+-- The keys also come first in the Sort below a Gather Merge.
+set parallel_setup_cost TO 0;
+set parallel_tuple_cost TO 0;
+set min_parallel_table_scan_size = 0;
+set max_parallel_workers_per_gather = 2;
+explain (verbose, costs off)
+select ten, sum(unique1 order by two, four) from tenk1 group by ten;
+reset max_parallel_workers_per_gather;
+reset min_parallel_table_scan_size;
+reset parallel_tuple_cost;
+reset parallel_setup_cost;
+
+-- The keys also come first in other plan shapes; some of them need an extra
+-- projection node for it.  These queries are run as well, since their
+-- results depend on the order the aggregates see.
+create temp table agg_key (g int, k int, v text);
+insert into agg_key values (1, 3, 'c'), (1, 1, 'a'), (1, 2, 'b'),
+                           (2, 2, 'b'), (2, 1, 'a');
+create temp table agg_key2 (g int, k int, v text);
+insert into agg_key2 values (0, 3, 'p'), (0, 1, 'q');
+analyze agg_key;
+analyze agg_key2;
+
+-- A subquery that is not pulled up produces its columns in the order it is
+-- written with, so a Subquery Scan is kept to bring the keys to the front.
+explain (verbose, costs off)
+select g, string_agg(v, ',' order by g, k)
+from (select g, v, k from agg_key offset 0) s group by g order by g;
+select g, string_agg(v, ',' order by g, k)
+from (select g, v, k from agg_key offset 0) s group by g order by g;
+
+-- A sort key from the nullable side of an outer join.  Unmatched rows sort
+-- last, because ASC puts NULLs last.
+explain (verbose, costs off)
+select a.g, string_agg(a.v, ',' order by b.k, a.k)
+from agg_key a left join agg_key2 b on a.k = b.k
+group by a.g order by a.g;
+select a.g, string_agg(a.v, ',' order by b.k, a.k)
+from agg_key a left join agg_key2 b on a.k = b.k
+group by a.g order by a.g;
+
+-- An Append node cannot change the column order of its inputs, so a UNION
+-- ALL gets a Result node that brings the keys to the front.
+explain (verbose, costs off)
+select g, string_agg(v, ',' order by g, k)
+from (select g, k, v from agg_key union all select g, k, v from agg_key2) u
+group by g order by g;
+select g, string_agg(v, ',' order by g, k)
+from (select g, k, v from agg_key union all select g, k, v from agg_key2) u
+group by g order by g;
+
+-- The same for an inheritance table.
+create temp table agg_key_child () inherits (agg_key);
+insert into agg_key_child values (1, 4, 'd'), (2, 3, 'c');
+analyze agg_key_child;
+explain (verbose, costs off)
+select g, string_agg(v, ',' order by g, k) from agg_key group by g order by g;
+select g, string_agg(v, ',' order by g, k) from agg_key group by g order by g;
+
+-- For a partitioned table the scans are planned with the new order, so no
+-- Result node is needed.
+create temp table agg_part (g int, k int, v text) partition by list (g);
+create temp table agg_part1 partition of agg_part for values in (1);
+create temp table agg_part2 partition of agg_part for values in (2);
+insert into agg_part values (1, 3, 'c'), (1, 1, 'a'), (1, 2, 'b'),
+                            (2, 2, 'b'), (2, 1, 'a');
+explain (verbose, costs off)
+select g, string_agg(v, ',' order by g, k) from agg_part group by g order by g;
+select g, string_agg(v, ',' order by g, k) from agg_part group by g order by g;
+
+drop table agg_part;
+drop table agg_key_child;
+drop table agg_key2;
+drop table agg_key;
+
 --
 -- Test cases with FILTER clause
 --
