Skip to content

Commit 4169850

Browse files
committed
Trim ORDER BY/DISTINCT aggregate pathkeys in gather_grouping_paths
Similar to d8a2953, trim off any PathKeys which are for ORDER BY / DISTINCT aggregate functions from the PathKey List for the Gather Merge paths created by gather_grouping_paths(). These additional PathKeys are not valid to use after grouping has taken place as these PathKeys belong to columns which are inputs to an aggregate function and, therefore are unavailable after aggregation. Reported-by: Alexander Lakhin Discussion: https://postgr.es/m/cf63174c-8c89-3953-cb49-48f41f74941a@gmail.com Backpatch-through: 16, where 1349d27 was added
1 parent 4665ceb commit 4169850

File tree

1 file changed

+15
-4
lines changed

1 file changed

+15
-4
lines changed

src/backend/optimizer/plan/planner.c

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7320,6 +7320,17 @@ gather_grouping_paths(PlannerInfo *root, RelOptInfo *rel)
73207320
{
73217321
ListCell *lc;
73227322
Path *cheapest_partial_path;
7323+
List *groupby_pathkeys;
7324+
7325+
/*
7326+
* This occurs after any partial aggregation has taken place, so trim off
7327+
* any pathkeys added for ORDER BY / DISTINCT aggregates.
7328+
*/
7329+
if (list_length(root->group_pathkeys) > root->num_groupby_pathkeys)
7330+
groupby_pathkeys = list_copy_head(root->group_pathkeys,
7331+
root->num_groupby_pathkeys);
7332+
else
7333+
groupby_pathkeys = root->group_pathkeys;
73237334

73247335
/* Try Gather for unordered paths and Gather Merge for ordered ones. */
73257336
generate_useful_gather_paths(root, rel, true);
@@ -7334,7 +7345,7 @@ gather_grouping_paths(PlannerInfo *root, RelOptInfo *rel)
73347345
int presorted_keys;
73357346
double total_groups;
73367347

7337-
is_sorted = pathkeys_count_contained_in(root->group_pathkeys,
7348+
is_sorted = pathkeys_count_contained_in(groupby_pathkeys,
73387349
path->pathkeys,
73397350
&presorted_keys);
73407351

@@ -7360,13 +7371,13 @@ gather_grouping_paths(PlannerInfo *root, RelOptInfo *rel)
73607371
*/
73617372
if (presorted_keys == 0 || !enable_incremental_sort)
73627373
path = (Path *) create_sort_path(root, rel, path,
7363-
root->group_pathkeys,
7374+
groupby_pathkeys,
73647375
-1.0);
73657376
else
73667377
path = (Path *) create_incremental_sort_path(root,
73677378
rel,
73687379
path,
7369-
root->group_pathkeys,
7380+
groupby_pathkeys,
73707381
presorted_keys,
73717382
-1.0);
73727383

@@ -7375,7 +7386,7 @@ gather_grouping_paths(PlannerInfo *root, RelOptInfo *rel)
73757386
rel,
73767387
path,
73777388
rel->reltarget,
7378-
root->group_pathkeys,
7389+
groupby_pathkeys,
73797390
NULL,
73807391
&total_groups);
73817392

0 commit comments

Comments
 (0)