diff --git a/src/backend/optimizer/path/allpaths.c b/src/backend/optimizer/path/allpaths.c index b7723481b0..15c45202f9 100644 --- a/src/backend/optimizer/path/allpaths.c +++ b/src/backend/optimizer/path/allpaths.c @@ -2719,6 +2719,8 @@ generate_gather_paths(PlannerInfo *root, RelOptInfo *rel, bool override_rows) { Path *subpath = (Path *) lfirst(lc); GatherMergePath *path; + bool is_sorted; + int presorted_keys; if (subpath->pathkeys == NIL) continue; @@ -2727,6 +2729,33 @@ generate_gather_paths(PlannerInfo *root, RelOptInfo *rel, bool override_rows) path = create_gather_merge_path(root, rel, subpath, rel->reltarget, subpath->pathkeys, NULL, rowsp); add_path(rel, &path->path); + + /* consider incremental sort */ + is_sorted = pathkeys_common_contained_in(root->sort_pathkeys, + subpath->pathkeys, &presorted_keys); + + if (!is_sorted && (presorted_keys > 0)) + { + elog(WARNING, "adding incremental sort + gather merge path"); + + /* Also consider incremental sort. */ + subpath = (Path *) create_incremental_sort_path(root, + rel, + subpath, + root->sort_pathkeys, + presorted_keys, + -1); + + subpath->total_cost = 100.0; + + path = create_gather_merge_path(root, rel, subpath, rel->reltarget, + subpath->pathkeys, NULL, rowsp); + + path->path.total_cost = 120.0; + + add_path(rel, &path->path); + } + } }