From 234e23f237ad78000fa9bf7d9432aef67d161c63 Mon Sep 17 00:00:00 2001 From: zhenglong li Date: Sat, 15 Aug 2026 13:55:00 +0800 Subject: [PATCH v7 2/2] Consider window functions when reordering GROUP BY items preprocess_groupclause() orders the GROUP BY items to match the query's ORDER BY clause, so that a single sort can serve both the grouping step and the final ordering. However, when the query contains window functions, the sort performed directly above the grouping step is the one required by the first window clause, not the one for ORDER BY, which is only performed above the WindowAgg nodes. Unless the window's sort requirements happened to coincide with a prefix of the ORDER BY clause, an additional sort was needed to provide the first WindowAgg with correctly ordered input. Teach get_useful_group_keys_orderings() to also offer the GROUP BY keys reordered to match the sort order of the first active window, ie its PARTITION BY keys followed by its ORDER BY keys, as one more candidate ordering. The remaining GROUP BY keys keep the order preprocess_groupclause() gave them, which matches the query's ORDER BY as far as possible; since WindowAgg nodes preserve their input ordering, this can additionally save the final sort. For example, the query SELECT a, b, count(*) OVER (PARTITION BY b) FROM t GROUP BY a, b; previously sorted twice: once by (a, b) for the grouping step and again by (b) for the WindowAgg. Grouping in the order (b, a) allows a single sort to serve both. With an ORDER BY that does not lead with the window's sort keys, such as adding "ORDER BY a" to the query above, the sort count similarly drops from three to two. We match the first window only because it alone can share a sort with the grouping step: select_active_windows() has already fixed the windows' evaluation order, placing the window with the strongest sort requirements first, directly above the grouping step. Satisfying its requirements may satisfy subsequent windows too, since windows whose requirements form a prefix of another's are evaluated later. The window's ordering is only offered as a candidate, rather than applied to root->processed_groupClause up front, because the GROUP BY pathkeys also serve as query_pathkeys, which guide the planning of the scan/join steps below the grouping step. If they took on the window's ordering, those steps would be steered towards it even where the grouping step can't provide it as cheaply as a sort above the grouping step can. For instance, with an index on (a, b) and SELECT a, count(*), sum(count(*)) OVER (ORDER BY a DESC) FROM t JOIN s USING (a, b) GROUP BY a; grouping by a DESC up front lost the plan that merge-joins off the index in ascending order in parallel and groups the result, falling back to a plan almost twice as expensive, although the window needs a sort either way. Keeping the original ordering as well, and letting the cost decide, retains that plan. Like the other alternative orderings of the GROUP BY keys, this one is considered only if enable_group_by_reordering is on. gather_grouping_paths() likewise sorts the partial paths by the window's ordering of the GROUP BY keys too, in addition to the original one, so that the sort can be done by the parallel workers below the Gather Merge rather than by the leader. The window's sort direction and NULLS ordering need not match those of the GROUP BY items, which the parser takes from a matching ORDER BY item or leaves at the default. So with SELECT a, b, c, count(*) OVER (PARTITION BY b ORDER BY c DESC) FROM t GROUP BY a, b, c; the GROUP BY item c sorts ascending. Since grouping only requires equal values to be adjacent, the reordered GROUP BY keys take on the window's c DESC, using the preceding commit's matching of pathkeys that ignores sort direction, so that a single sort by (b, c DESC, a) serves both steps. That matching requires the same equivalence class and operator family, so a window's ORDER BY ... USING with an operator from another operator family is not adopted, even if both families share the equality operator: under a nondeterministic collation, text_pattern_ops' ~<~ compares bytes, so sorting by it might not bring equal values together. Note that the sort cost model is insensitive to column cardinalities, so it costs a sort by (b, a) the same as one by (a, b), and the window's ordering wins whenever it saves a sort above the grouping step. Moving a low-cardinality window key to the front of a large grouping sort defeats the leading-key specializations in tuplesort and can cost more than the eliminated sort saved when the number of groups is small relative to the input. This is mitigated in practice because a small number of groups is also when hash aggregation tends to win, whereas sorted aggregation tends to be chosen when groups are numerous, which is exactly when the eliminated sort is large. Mention the window ordering in the documentation of enable_group_by_reordering. Suggested-by: Henson Choi Reviewed-by: Henson Choi --- doc/src/sgml/config.sgml | 3 +- src/backend/optimizer/path/pathkeys.c | 90 ++- src/backend/optimizer/plan/planner.c | 129 ++-- src/include/optimizer/paths.h | 1 + .../regress/expected/collate.icu.utf8.out | 30 + src/test/regress/expected/window.out | 566 ++++++++++++++++++ src/test/regress/sql/collate.icu.utf8.sql | 12 + src/test/regress/sql/window.sql | 253 ++++++++ 8 files changed, 1027 insertions(+), 57 deletions(-) diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml index 78f713864c2..8fd6027d5d4 100644 --- a/doc/src/sgml/config.sgml +++ b/doc/src/sgml/config.sgml @@ -5988,7 +5988,8 @@ ANY num_sync (