From fa10999368e31e2e569842ce856e9ce9529ff3f9 Mon Sep 17 00:00:00 2001
From: Richard Guo <guofenglinux@gmail.com>
Date: Fri, 23 Aug 2024 16:55:32 +0900
Subject: [PATCH v1] Avoid unnecessary post-sort projection

---
 src/backend/optimizer/plan/planner.c          |  6 +++--
 .../regress/expected/select_distinct_on.out   | 26 +++++++++----------
 2 files changed, 16 insertions(+), 16 deletions(-)

diff --git a/src/backend/optimizer/plan/planner.c b/src/backend/optimizer/plan/planner.c
index b5827d3980..f7bfe57675 100644
--- a/src/backend/optimizer/plan/planner.c
+++ b/src/backend/optimizer/plan/planner.c
@@ -5301,7 +5301,8 @@ create_ordered_paths(PlannerInfo *root,
 		}
 
 		/* Add projection step if needed */
-		if (sorted_path->pathtarget != target)
+		if (sorted_path->pathtarget != target &&
+			!equal(sorted_path->pathtarget->exprs, target->exprs))
 			sorted_path = apply_projection_to_path(root, ordered_rel,
 												   sorted_path, target);
 
@@ -5379,7 +5380,8 @@ create_ordered_paths(PlannerInfo *root,
 										 &total_groups);
 
 			/* Add projection step if needed */
-			if (sorted_path->pathtarget != target)
+			if (sorted_path->pathtarget != target &&
+				!equal(sorted_path->pathtarget->exprs, target->exprs))
 				sorted_path = apply_projection_to_path(root, ordered_rel,
 													   sorted_path, target);
 
diff --git a/src/test/regress/expected/select_distinct_on.out b/src/test/regress/expected/select_distinct_on.out
index b2978c1114..958381afe5 100644
--- a/src/test/regress/expected/select_distinct_on.out
+++ b/src/test/regress/expected/select_distinct_on.out
@@ -81,13 +81,12 @@ select distinct on (1) floor(random()) as r, f1 from int4_tbl order by 1,2;
 EXPLAIN (COSTS OFF)
 SELECT DISTINCT ON (four) four,two
    FROM tenk1 WHERE four = 0 ORDER BY 1;
-            QUERY PLAN            
-----------------------------------
- Result
-   ->  Limit
-         ->  Seq Scan on tenk1
-               Filter: (four = 0)
-(4 rows)
+         QUERY PLAN         
+----------------------------
+ Limit
+   ->  Seq Scan on tenk1
+         Filter: (four = 0)
+(3 rows)
 
 -- and check the result of the above query is correct
 SELECT DISTINCT ON (four) four,two
@@ -115,11 +114,10 @@ SELECT DISTINCT ON (four) four,two
 EXPLAIN (COSTS OFF)
 SELECT DISTINCT ON (four) four,hundred
    FROM tenk1 WHERE four = 0 ORDER BY 1,2;
-                     QUERY PLAN                      
------------------------------------------------------
- Result
-   ->  Limit
-         ->  Index Scan using tenk1_hundred on tenk1
-               Filter: (four = 0)
-(4 rows)
+                  QUERY PLAN                   
+-----------------------------------------------
+ Limit
+   ->  Index Scan using tenk1_hundred on tenk1
+         Filter: (four = 0)
+(3 rows)
 
-- 
2.43.0

