diff --git a/src/backend/optimizer/path/pathkeys.c b/src/backend/optimizer/path/pathkeys.c index 82ff31273b..f89745f063 100644 --- a/src/backend/optimizer/path/pathkeys.c +++ b/src/backend/optimizer/path/pathkeys.c @@ -369,6 +369,7 @@ group_keys_reorder_by_pathkeys(List *pathkeys, List **group_pathkeys, { List *new_group_pathkeys = NIL, *new_group_clauses = NIL; + List *grouping_pathkeys = list_copy_head(*group_pathkeys, num_groupby_pathkeys); ListCell *lc; int n; @@ -395,7 +396,7 @@ group_keys_reorder_by_pathkeys(List *pathkeys, List **group_pathkeys, * there is no sortclause reference for some reason. */ if (foreach_current_index(lc) >= num_groupby_pathkeys || - !list_member_ptr(*group_pathkeys, pathkey) || + !list_member_ptr(grouping_pathkeys, pathkey) || pathkey->pk_eclass->ec_sortref == 0) break; @@ -429,6 +430,7 @@ group_keys_reorder_by_pathkeys(List *pathkeys, List **group_pathkeys, *group_clauses = list_concat_unique_ptr(new_group_clauses, *group_clauses); + pfree(grouping_pathkeys); return n; }