diff --git a/src/backend/optimizer/path/pathkeys.c b/src/backend/optimizer/path/pathkeys.c index fdb60aaa8d..73883f1413 100644 --- a/src/backend/optimizer/path/pathkeys.c +++ b/src/backend/optimizer/path/pathkeys.c @@ -1114,6 +1114,44 @@ build_join_pathkeys(PlannerInfo *root, return truncate_useless_pathkeys(root, joinrel, outer_pathkeys); } +/* + * get_pathkeys_in_target + * Return a list which is a prefix of pathkeys containing all 'pathkeys' + * elements up until the first PathKey which cannot be found in the given + * PathTarget. + */ +List * +get_pathkeys_in_target(List *pathkeys, PathTarget *target, Relids relids) +{ + ListCell *lc; + List *new_pathkeys = NIL; + + foreach (lc, pathkeys) + { + ListCell *lc2; + PathKey *pathkey = lfirst_node(PathKey, lc); + bool found = false; + + foreach (lc2, target->exprs) + { + Expr *expr = lfirst(lc2); + + if (find_ec_member_matching_expr(pathkey->pk_eclass, expr, relids)) + { + found = true; + break; + } + } + + if (found) + new_pathkeys = lappend(new_pathkeys, pathkey); + else + break; + } + + return new_pathkeys; +} + /**************************************************************************** * PATHKEYS AND SORT CLAUSES ****************************************************************************/ diff --git a/src/backend/optimizer/util/pathnode.c b/src/backend/optimizer/util/pathnode.c index 211ba65389..9d5bd40fe4 100644 --- a/src/backend/optimizer/util/pathnode.c +++ b/src/backend/optimizer/util/pathnode.c @@ -3133,10 +3133,18 @@ create_agg_path(PlannerInfo *root, pathnode->path.parallel_safe = rel->consider_parallel && subpath->parallel_safe; pathnode->path.parallel_workers = subpath->parallel_workers; + + /* + * For AGG_SORTED, some pathkeys may belong to aggregated expressions, so we + * only take the subpath's pathkeys up until the first pathkey we can no + * longer find in the AggPath's target list. + */ if (aggstrategy == AGG_SORTED) - pathnode->path.pathkeys = subpath->pathkeys; /* preserves order */ + pathnode->path.pathkeys = get_pathkeys_in_target(subpath->pathkeys, target, + rel->relids); else pathnode->path.pathkeys = NIL; /* output is unordered */ + pathnode->subpath = subpath; pathnode->aggstrategy = aggstrategy; diff --git a/src/include/optimizer/paths.h b/src/include/optimizer/paths.h index 50bc3b503a..0ae88b5e4d 100644 --- a/src/include/optimizer/paths.h +++ b/src/include/optimizer/paths.h @@ -228,6 +228,8 @@ extern List *build_join_pathkeys(PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, List *outer_pathkeys); +extern List *get_pathkeys_in_target(List *pathkeys, PathTarget *target, + Relids relids); extern List *make_pathkeys_for_sortclauses(PlannerInfo *root, List *sortclauses, List *tlist);