From cb8a3247fbb0db9527cb53930a4a2a8c67efdb52 Mon Sep 17 00:00:00 2001
From: Jelte Fennema-Nio <postgres@jeltef.nl>
Date: Thu, 26 Nov 2026 00:02:59 +0100
Subject: [PATCH v4 6/8] postgres_fdw: Add test for sorting below a cheap local
 qual

The existing test with an expensive local qual doesn't show where the
sort is done when only the cost of the sort matters, because the cost
of the qual hides the difference. So this adds one with a cheap local
qual, to make the plan change in the follow on commit visible.
---
 contrib/postgres_fdw/expected/postgres_fdw.out | 14 ++++++++++++++
 contrib/postgres_fdw/sql/postgres_fdw.sql      |  6 ++++++
 2 files changed, 20 insertions(+)

diff --git a/contrib/postgres_fdw/expected/postgres_fdw.out b/contrib/postgres_fdw/expected/postgres_fdw.out
index 5b21910bfbb..125f5273d24 100644
--- a/contrib/postgres_fdw/expected/postgres_fdw.out
+++ b/contrib/postgres_fdw/expected/postgres_fdw.out
@@ -324,6 +324,20 @@ ORDER BY c2;
    Remote SQL: SELECT c2, count(*) FROM "S 1"."T 1" GROUP BY 1 ORDER BY c2 ASC NULLS LAST
 (5 rows)
 
+-- A local qual also means that a local sort has fewer rows to sort than a
+-- remote one, which has to sort all rows that we retrieve.  With a cheap
+-- qual, where the sort is done is decided by the cost of the sort itself.
+ALTER FUNCTION local_filter(int) COST 1;
+EXPLAIN (VERBOSE, COSTS OFF)
+SELECT c1 FROM ft1 WHERE local_filter(c1) ORDER BY c1;
+                                QUERY PLAN                                 
+---------------------------------------------------------------------------
+ Foreign Scan on public.ft1
+   Output: c1
+   Filter: local_filter(ft1.c1)
+   Remote SQL: SELECT "C 1" FROM "S 1"."T 1" ORDER BY "C 1" ASC NULLS LAST
+(4 rows)
+
 DROP FUNCTION local_filter(int);
 DROP FUNCTION local_project(int);
 -- Without remote estimates we don't know what join strategy the foreign
diff --git a/contrib/postgres_fdw/sql/postgres_fdw.sql b/contrib/postgres_fdw/sql/postgres_fdw.sql
index da6e79546be..0164457b56a 100644
--- a/contrib/postgres_fdw/sql/postgres_fdw.sql
+++ b/contrib/postgres_fdw/sql/postgres_fdw.sql
@@ -281,6 +281,12 @@ SELECT local_project(c2), count(*) FROM ft1 GROUP BY c2 ORDER BY c2;
 EXPLAIN (VERBOSE, COSTS OFF)
 SELECT c2, count(*) FROM ft1 GROUP BY c2 HAVING local_filter(count(*)::int)
 ORDER BY c2;
+-- A local qual also means that a local sort has fewer rows to sort than a
+-- remote one, which has to sort all rows that we retrieve.  With a cheap
+-- qual, where the sort is done is decided by the cost of the sort itself.
+ALTER FUNCTION local_filter(int) COST 1;
+EXPLAIN (VERBOSE, COSTS OFF)
+SELECT c1 FROM ft1 WHERE local_filter(c1) ORDER BY c1;
 DROP FUNCTION local_filter(int);
 DROP FUNCTION local_project(int);
 
-- 
2.56.1

