From 9f689d942e6ffa5f213367dfda3e1162a61b57be Mon Sep 17 00:00:00 2001 From: Shihao Date: Sat, 3 Oct 2026 22:00:46 -0600 Subject: [PATCH v2 1/2] Don't let single-child setop Appends inherit pathkeys When all but one input of a UNION is proven empty, or the right input of an EXCEPT ALL is, we use an Append with a single child. create_append_path() copies the child's pathkeys in that case, but in a setop tree those need not match the Append's targetlist, and planning could fail with "could not find pathkey item to sort". Clear the pathkeys of such Appends. Bug: #19742 Reported-by: Junwen AN --- src/backend/optimizer/prep/prepunion.c | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/backend/optimizer/prep/prepunion.c b/src/backend/optimizer/prep/prepunion.c index b136f12ff3b..9d0acad49f0 100644 --- a/src/backend/optimizer/prep/prepunion.c +++ b/src/backend/optimizer/prep/prepunion.c @@ -862,6 +862,12 @@ generate_union_paths(SetOperationStmt *op, PlannerInfo *root, apath = (Path *) create_append_path(root, result_rel, cheapest, NIL, NULL, 0, false, -1); + /* + * A single-child Append inherits its child's pathkeys, but those might + * not match this setop's targetlist. + */ + apath->pathkeys = NIL; + /* * Initialize the result row estimate to the total input size. This is * correct for UNION ALL; for the UNION case it is overwritten below with @@ -1225,6 +1231,9 @@ generate_nonunion_paths(SetOperationStmt *op, PlannerInfo *root, append, NIL, NULL, 0, false, -1); + /* as in generate_union_paths, don't trust child pathkeys */ + apath->pathkeys = NIL; + add_path(result_rel, apath); return result_rel; -- 2.37.1 (Apple Git-137.1)