From 101e64979f476b376e40fd4995361f194a5414b5 Mon Sep 17 00:00:00 2001
From: Richard Guo <guofenglinux@gmail.com>
Date: Tue, 4 Nov 2025 18:57:26 +0900
Subject: [PATCH v1] Fix generate_union_paths()

---
 src/backend/optimizer/prep/prepunion.c | 8 ++++++--
 src/test/regress/expected/union.out    | 6 +++---
 2 files changed, 9 insertions(+), 5 deletions(-)

diff --git a/src/backend/optimizer/prep/prepunion.c b/src/backend/optimizer/prep/prepunion.c
index 55665824179..464fc15d115 100644
--- a/src/backend/optimizer/prep/prepunion.c
+++ b/src/backend/optimizer/prep/prepunion.c
@@ -773,6 +773,12 @@ generate_union_paths(SetOperationStmt *op, PlannerInfo *root,
 		RelOptInfo *rel = lfirst(lc);
 		Path	   *ordered_path;
 
+		/*
+		 * Include this child's relids in the resulting relid set, even if the
+		 * child is a dummy relation.
+		 */
+		relids = bms_add_members(relids, rel->relids);
+
 		/* Skip any UNION children that are proven not to yield any rows */
 		if (is_dummy_rel(rel))
 			continue;
@@ -815,8 +821,6 @@ generate_union_paths(SetOperationStmt *op, PlannerInfo *root,
 				partial_pathlist = lappend(partial_pathlist,
 										   linitial(rel->partial_pathlist));
 		}
-
-		relids = bms_add_members(relids, rel->relids);
 	}
 
 	/* Build result relation. */
diff --git a/src/test/regress/expected/union.out b/src/test/regress/expected/union.out
index fb77d108337..4533967e84a 100644
--- a/src/test/regress/expected/union.out
+++ b/src/test/regress/expected/union.out
@@ -1260,14 +1260,14 @@ SELECT four FROM tenk1 WHERE 1=2
 UNION
 SELECT ten FROM tenk1 WHERE 1=2
 ORDER BY 1;
-              QUERY PLAN              
---------------------------------------
+                                       QUERY PLAN                                        
+-----------------------------------------------------------------------------------------
  Sort
    Output: unnamed_subquery.two
    Sort Key: unnamed_subquery.two
    ->  Result
          Output: unnamed_subquery.two
-         Replaces: Aggregate
+         Replaces: Aggregate on unnamed_subquery, unnamed_subquery_1, unnamed_subquery_2
          One-Time Filter: false
 (7 rows)
 
-- 
2.39.5 (Apple Git-154)

