From b2f6cd386a906064ccbf213d2d7abfdc299a9b59 Mon Sep 17 00:00:00 2001 From: Chengpeng Yan Date: Sat, 5 Dec 2026 15:45:59 +0800 Subject: [PATCH v3 2/2] Postpone more sort outputs when a projection is needed anyway When make_sort_input_target() already adds a post-sort projection and there is a LIMIT, also postpone plain target expressions whose inputs pass through the Sort anyway. This narrows the sorted tuples without adding sort columns or a projection node, and avoids evaluating those expressions for rows discarded by LIMIT. --- src/backend/optimizer/plan/planner.c | 63 ++++++++++++++++++++++++++++ src/test/regress/expected/limit.out | 18 ++++++++ src/test/regress/sql/limit.sql | 6 +++ 3 files changed, 87 insertions(+) diff --git a/src/backend/optimizer/plan/planner.c b/src/backend/optimizer/plan/planner.c index bcb7a720b49..354cffa4488 100644 --- a/src/backend/optimizer/plan/planner.c +++ b/src/backend/optimizer/plan/planner.c @@ -255,6 +255,7 @@ static List *make_pathkeys_for_window(PlannerInfo *root, WindowClause *wc, static PathTarget *make_sort_input_target(PlannerInfo *root, PathTarget *final_target, bool *have_postponed_srfs); +static bool is_sort_input_value(Expr *expr); static void adjust_paths_for_srfs(PlannerInfo *root, RelOptInfo *rel, List *targets, List *targets_contain_srfs); static void add_paths_to_grouping_rel(PlannerInfo *root, RelOptInfo *input_rel, @@ -6699,6 +6700,8 @@ typedef struct SortInputCol * to have to evaluate the expressions for every row anyway), or if there are * any volatile or set-returning expressions (since once we've put in a * projection at all, it won't cost any more to postpone more stuff). + * If there is a LIMIT and we're adding a projection anyway, we also postpone + * plain columns whose inputs already pass through the Sort. * * Another issue that could potentially be considered here is that * evaluating tlist expressions could result in data that's either wider @@ -6874,6 +6877,52 @@ make_sort_input_target(PlannerInfo *root, PVC_INCLUDE_WINDOWFUNCS | PVC_INCLUDE_PLACEHOLDERS); + if (!postpone_srfs && + (parse->limitCount || root->tuple_fraction > 0)) + { + List *sort_inputs = list_copy(postponable_vars); + + /* Values the Sort carries anyway */ + for (i = 0; i < ncols; i++) + { + SortInputCol *col = &cols[i]; + + if (!col->postpone && is_sort_input_value(col->expr)) + sort_inputs = lappend(sort_inputs, col->expr); + } + + /* Postpone plain columns computable from those */ + for (i = 0; i < ncols; i++) + { + SortInputCol *col = &cols[i]; + List *col_vars; + bool available = true; + + if (col->postpone || col->sortgroupref != 0 || col->is_srf || + is_sort_input_value(col->expr)) + continue; + + col_vars = pull_var_clause((Node *) col->expr, + PVC_INCLUDE_AGGREGATES | + PVC_INCLUDE_WINDOWFUNCS | + PVC_INCLUDE_PLACEHOLDERS); + foreach(lc, col_vars) + { + if (!list_member(sort_inputs, lfirst(lc))) + { + available = false; + break; + } + } + list_free(col_vars); + + if (available) + col->postpone = true; + } + + list_free(sort_inputs); + } + /* Construct sort-input target, accumulating cost and width as we go */ input_target = create_empty_pathtarget(); @@ -6905,6 +6954,20 @@ make_sort_input_target(PlannerInfo *root, return input_target; } +/* + * is_sort_input_value + * Is expr a leaf node type that pull_var_clause() returns here? + */ +static bool +is_sort_input_value(Expr *expr) +{ + return IsA(expr, Var) || + IsA(expr, PlaceHolderVar) || + IsA(expr, Aggref) || + IsA(expr, GroupingFunc) || + IsA(expr, WindowFunc); +} + /* * get_cheapest_fractional_path * Find the cheapest path for retrieving a specified fraction of all diff --git a/src/test/regress/expected/limit.out b/src/test/regress/expected/limit.out index e3bcc680653..1c8e7841f14 100644 --- a/src/test/regress/expected/limit.out +++ b/src/test/regress/expected/limit.out @@ -491,6 +491,24 @@ select unique1, unique2, generate_series(1,10) 0 | 9998 | 7 (7 rows) +-- Also postpone unique2 * 2 and tenthous * 2, but not stringu1 || 'x' +explain (verbose, costs off) +select unique1, unique2 + nextval('testseq'), unique2 * 2, tenthous * 2, + stringu1 || 'x' + from tenk1 order by tenthous limit 10; + QUERY PLAN +----------------------------------------------------------------------------------------------------------------------------------------------- + Limit + Output: unique1, ((unique2 + nextval('testseq'::regclass))), ((unique2 * 2)), ((tenthous * 2)), (((stringu1)::text || 'x'::text)), tenthous + -> Result + Output: unique1, (unique2 + nextval('testseq'::regclass)), (unique2 * 2), (tenthous * 2), (((stringu1)::text || 'x'::text)), tenthous + -> Sort + Output: unique1, (((stringu1)::text || 'x'::text)), tenthous, unique2 + Sort Key: tenk1.tenthous + -> Seq Scan on public.tenk1 + Output: unique1, ((stringu1)::text || 'x'::text), tenthous, unique2 +(9 rows) + -- use of random() is to keep planner from folding the expressions together explain (verbose, costs off) select generate_series(0,2) as s1, generate_series((random()*.1)::int,2) as s2; diff --git a/src/test/regress/sql/limit.sql b/src/test/regress/sql/limit.sql index 603910fe6d1..c3511637da4 100644 --- a/src/test/regress/sql/limit.sql +++ b/src/test/regress/sql/limit.sql @@ -131,6 +131,12 @@ select unique1, unique2, generate_series(1,10) select unique1, unique2, generate_series(1,10) from tenk1 order by tenthous limit 7; +-- Also postpone unique2 * 2 and tenthous * 2, but not stringu1 || 'x' +explain (verbose, costs off) +select unique1, unique2 + nextval('testseq'), unique2 * 2, tenthous * 2, + stringu1 || 'x' + from tenk1 order by tenthous limit 10; + -- use of random() is to keep planner from folding the expressions together explain (verbose, costs off) select generate_series(0,2) as s1, generate_series((random()*.1)::int,2) as s2; -- 2.50.1 (Apple Git-155)