Hi,

Commit a8ccf4e93a7e taught the planner to reorder DISTINCT keys to
match an input path's ordering.
Since the order of the DISTINCT keys does not affect which rows belong
to the same group, the planner
can use an existing ordering directly or use incremental sort when
only part of the ordering is available.

I found a DISTINCT ON case where the index already provides the full
ordering needed below Unique,
but the planner only recognizes the DISTINCT keys as presorted:

CREATE TABLE distinct_on_demo (x int, y int, z int);
INSERT INTO distinct_on_demo
SELECT i % 10, i % 10, i % 10
FROM generate_series(1, 1000) AS g(i);
INSERT INTO distinct_on_demo VALUES (0, 0, 21), (0, 0, 22);
CREATE INDEX distinct_on_demo_xyz_idx
    ON distinct_on_demo (x, y, z DESC);
ANALYZE distinct_on_demo;
SET enable_seqscan = off;

EXPLAIN (COSTS OFF)
SELECT DISTINCT ON (y, x) x, y, z
FROM distinct_on_demo
ORDER BY y, x, z DESC;
                                      QUERY PLAN
--------------------------------------------------------------------------------------
 Sort
   Sort Key: y, x, z DESC
   ->  Unique
         ->  Incremental Sort
               Sort Key: x, y, z DESC
               Presorted Key: x, y
               ->  Index Only Scan using distinct_on_demo_xyz_idx on
distinct_on_demo
(7 rows)

The required ordering is (y, x, z DESC), and the index provides (x, y, z DESC).
After reordering the DISTINCT keys to (x, y), the index already puts
all rows in each group together and orders them by z DESC.
For example, Unique should keep (0, 0, 22) for the (0, 0) group.

However, truncate_useless_pathkeys() only counts (x, y) as useful for
DISTINCT, so it drops z DESC from the index path's advertised
ordering.
The planner can then add an incremental sort below Unique to sort each
(x, y) group by z DESC, even though the index already provides that
ordering.

The attached patch makes truncate_useless_pathkeys() and
get_useful_pathkeys_for_distinct() use the same prefix-matching rules.
Once all DISTINCT keys have been matched in any order, the planner can
also reuse the remaining ORDER BY keys that match in their original
order.
In this example, that lets Unique consume the index ordering directly:
                                   QUERY PLAN
--------------------------------------------------------------------------------
 Sort
   Sort Key: y, x, z DESC
   ->  Unique
         ->  Index Only Scan using distinct_on_demo_xyz_idx on distinct_on_demo
(4 rows)

The remaining sort is above Unique and applies the requested output
order to the deduplicated rows.


-- 
Tender Wang
From 61062968701863d2f30041d13d97bf17b51eb8f4 Mon Sep 17 00:00:00 2001
From: Tender Wang <[email protected]>
Date: Wed, 25 Nov 2026 13:51:46 +0800
Subject: [PATCH] Preserve presorted ORDER BY keys when reordering DISTINCT ON
 keys

Pathkey truncation can discard sort keys that follow the DISTINCT ON
keys, even when the input already provides the full ordering needed by
Unique after reordering. This can cause an unnecessary sort below Unique.

Use the same prefix-matching rules when truncating pathkeys and when
building DISTINCT paths. Allow the DISTINCT ON keys to be reordered
and match the remaining ORDER BY keys in their original order, so
Unique still keeps the correct first row in each group.
---
 src/backend/optimizer/path/pathkeys.c         | 76 +++++++++++++++++--
 src/backend/optimizer/plan/planner.c          | 52 +++----------
 src/include/optimizer/paths.h                 |  4 +
 .../regress/expected/select_distinct_on.out   | 35 +++++++++
 src/test/regress/sql/select_distinct_on.sql   | 15 ++++
 5 files changed, 134 insertions(+), 48 deletions(-)

diff --git a/src/backend/optimizer/path/pathkeys.c 
b/src/backend/optimizer/path/pathkeys.c
index 50651813a11..35158cdd6b5 100644
--- a/src/backend/optimizer/path/pathkeys.c
+++ b/src/backend/optimizer/path/pathkeys.c
@@ -2198,6 +2198,71 @@ count_common_leading_pathkeys_unordered(List *keys1, 
List *keys2)
        return ncommon;
 }
 
+/*
+ * Return the required ordering for sort-based DISTINCT.  For DISTINCT ON,
+ * include any additional ORDER BY keys that determine which row to keep.
+ */
+List *
+get_distinct_required_pathkeys(PlannerInfo *root)
+{
+       if (root->parse->hasDistinctOn &&
+               list_length(root->sort_pathkeys) > 
list_length(root->distinct_pathkeys))
+               return root->sort_pathkeys;
+
+       return root->distinct_pathkeys;
+}
+
+/*
+ * Count the input pathkeys that can be used as the prefix of a reordered
+ * DISTINCT ordering.  DISTINCT keys may be permuted, but any remaining keys
+ * must match in order after all the DISTINCT keys have been matched.
+ */
+int
+count_presorted_distinct_pathkeys(PlannerInfo *root, List *needed_pathkeys,
+                                                               List *pathkeys)
+{
+       List       *distinct_pathkeys = root->distinct_pathkeys;
+       int                     ncommon = 0;
+       int                     ndistinct = list_length(distinct_pathkeys);
+       int                     ncheck = Min(list_length(pathkeys), 
list_length(needed_pathkeys));
+
+       if (distinct_pathkeys == NIL)
+               return 0;
+
+       /* Retain the traditional DISTINCT prefix when reordering is disabled. 
*/
+       if (!enable_distinct_reordering || needed_pathkeys == distinct_pathkeys)
+               return 
count_common_leading_pathkeys_unordered(distinct_pathkeys,
+                                                                               
                          pathkeys);
+
+       for (; ncommon < ncheck && ncommon < ndistinct; ncommon++)
+       {
+               PathKey    *pathkey = list_nth(pathkeys, ncommon);
+
+               if (!list_member_ptr(distinct_pathkeys, pathkey) ||
+                       !list_member_ptr(needed_pathkeys, pathkey))
+                       return ncommon;
+       }
+
+       /*
+        * Only interpret the trailing keys as an ORDER BY suffix when the
+        * required ordering starts with the DISTINCT keys.
+        */
+       if (ncommon == ndistinct && ncommon < ncheck &&
+               pathkeys_contained_in(distinct_pathkeys, needed_pathkeys))
+       {
+               for (; ncommon < ncheck; ncommon++)
+               {
+                       PathKey    *pathkey1 = list_nth(pathkeys, ncommon);
+                       PathKey    *pathkey2 = list_nth(needed_pathkeys, 
ncommon);
+
+                       if (pathkey1 != pathkey2)
+                               break;
+               }
+       }
+
+       return ncommon;
+}
+
 /*
  * truncate_useless_pathkeys
  *             Shorten the given PathKey List to just the useful PathKeys.  If 
all
@@ -2243,10 +2308,8 @@ truncate_useless_pathkeys(PlannerInfo *root,
        nuseful = Max(nuseful, nuseful2);
 
        /*
-        * Check if these pathkeys are useful for GROUP BY or DISTINCT.  The 
order
-        * of the pathkeys does not matter here as Unique and GroupAggregate for
-        * these operations can take advantage of Paths presorted by any of the
-        * GROUP BY/DISTINCT pathkeys.
+        * Check if these pathkeys are useful for GROUP BY or DISTINCT.  Their
+        * grouping keys can be reordered to take advantage of presorted input.
         */
        nuseful2 = count_common_leading_pathkeys_unordered(root->group_pathkeys,
                                                                                
                           pathkeys);
@@ -2254,8 +2317,9 @@ truncate_useless_pathkeys(PlannerInfo *root,
                return pathkeys;
 
        nuseful = Max(nuseful, nuseful2);
-       nuseful2 = 
count_common_leading_pathkeys_unordered(root->distinct_pathkeys,
-                                                                               
                           pathkeys);
+       nuseful2 = count_presorted_distinct_pathkeys(root,
+                                                                               
                get_distinct_required_pathkeys(root),
+                                                                               
                pathkeys);
 
        if (nuseful2 == ntotal)
                return pathkeys;
diff --git a/src/backend/optimizer/plan/planner.c 
b/src/backend/optimizer/plan/planner.c
index 568a1b2a346..71fa07fd120 100644
--- a/src/backend/optimizer/plan/planner.c
+++ b/src/backend/optimizer/plan/planner.c
@@ -5411,12 +5411,7 @@ create_final_distinct_paths(PlannerInfo *root, 
RelOptInfo *input_rel,
                ListCell   *lc;
                double          limittuples = root->distinct_pathkeys == NIL ? 
1.0 : -1.0;
 
-               if (parse->hasDistinctOn &&
-                       list_length(root->distinct_pathkeys) <
-                       list_length(root->sort_pathkeys))
-                       needed_pathkeys = root->sort_pathkeys;
-               else
-                       needed_pathkeys = root->distinct_pathkeys;
+               needed_pathkeys = get_distinct_required_pathkeys(root);
 
                foreach(lc, input_rel->pathlist)
                {
@@ -5539,7 +5534,8 @@ get_useful_pathkeys_for_distinct(PlannerInfo *root, List 
*needed_pathkeys,
                                                                 List 
*path_pathkeys)
 {
        List       *useful_pathkeys_list = NIL;
-       List       *useful_pathkeys = NIL;
+       List       *useful_pathkeys;
+       int                     npresorted;
 
        /* always include the given 'needed_pathkeys' */
        useful_pathkeys_list = lappend(useful_pathkeys_list,
@@ -5548,45 +5544,17 @@ get_useful_pathkeys_for_distinct(PlannerInfo *root, 
List *needed_pathkeys,
        if (!enable_distinct_reordering)
                return useful_pathkeys_list;
 
-       /*
-        * Scan the given 'path_pathkeys' and construct a list of PathKey nodes
-        * that match 'needed_pathkeys', but only up to the longest matching
-        * prefix.
-        *
-        * When we have DISTINCT ON, we must ensure that the resulting pathkey
-        * list matches initial distinctClause pathkeys; otherwise, it won't 
have
-        * the desired behavior.
-        */
-       foreach_node(PathKey, pathkey, path_pathkeys)
-       {
-               /*
-                * The PathKey nodes are canonical, so they can be checked for
-                * equality by simple pointer comparison.
-                */
-               if (!list_member_ptr(needed_pathkeys, pathkey))
-                       break;
-               if (root->parse->hasDistinctOn &&
-                       !list_member_ptr(root->distinct_pathkeys, pathkey))
-                       break;
-
-               useful_pathkeys = lappend(useful_pathkeys, pathkey);
-       }
-
-       /* If no match at all, no point in reordering needed_pathkeys */
-       if (useful_pathkeys == NIL)
+       npresorted = count_presorted_distinct_pathkeys(root, needed_pathkeys,
+                                                                               
                 path_pathkeys);
+       if (npresorted == 0)
                return useful_pathkeys_list;
 
-       /*
-        * If not full match, the resulting pathkey list is not useful without
-        * incremental sort.
-        */
-       if (list_length(useful_pathkeys) < list_length(needed_pathkeys) &&
-               !enable_incremental_sort)
+       /* A partial match only helps when incremental sort is available. */
+       if (!enable_incremental_sort && npresorted < 
list_length(needed_pathkeys))
                return useful_pathkeys_list;
 
-       /* Append the remaining PathKey nodes in needed_pathkeys */
-       useful_pathkeys = list_concat_unique_ptr(useful_pathkeys,
-                                                                               
         needed_pathkeys);
+       useful_pathkeys = list_copy_head(path_pathkeys, npresorted);
+       useful_pathkeys = list_concat_unique_ptr(useful_pathkeys, 
needed_pathkeys);
 
        /*
         * If the resulting pathkey list is the same as the 'needed_pathkeys',
diff --git a/src/include/optimizer/paths.h b/src/include/optimizer/paths.h
index 64f87da1674..4511aeeb28e 100644
--- a/src/include/optimizer/paths.h
+++ b/src/include/optimizer/paths.h
@@ -276,6 +276,10 @@ extern List *make_inner_pathkeys_for_merge(PlannerInfo 
*root,
 extern List *trim_mergeclauses_for_inner_pathkeys(PlannerInfo *root,
                                                                                
                  List *mergeclauses,
                                                                                
                  List *pathkeys);
+extern List *get_distinct_required_pathkeys(PlannerInfo *root);
+extern int     count_presorted_distinct_pathkeys(PlannerInfo *root,
+                                                                               
          List *needed_pathkeys,
+                                                                               
          List *pathkeys);
 extern List *truncate_useless_pathkeys(PlannerInfo *root,
                                                                           
RelOptInfo *rel,
                                                                           List 
*pathkeys);
diff --git a/src/test/regress/expected/select_distinct_on.out 
b/src/test/regress/expected/select_distinct_on.out
index 75b1e7d300f..5e6528b8401 100644
--- a/src/test/regress/expected/select_distinct_on.out
+++ b/src/test/regress/expected/select_distinct_on.out
@@ -245,4 +245,39 @@ SELECT DISTINCT ON (y, x) x, y FROM (select * from 
distinct_on_tbl order by x, z
 (10 rows)
 
 RESET enable_hashagg;
+-- Keep the ORDER BY suffix after reordering the DISTINCT ON keys.
+DROP INDEX distinct_on_tbl_x_y_idx;
+CREATE INDEX distinct_on_tbl_x_y_z_idx ON distinct_on_tbl (x, y, z DESC);
+INSERT INTO distinct_on_tbl VALUES (0, 0, 21), (0, 0, 22);
+ANALYZE distinct_on_tbl;
+SET enable_seqscan TO OFF;
+-- The index provides the full ordering needed below Unique.
+SET enable_incremental_sort TO OFF;
+EXPLAIN (COSTS OFF)
+SELECT DISTINCT ON (y, x) x, y, z FROM distinct_on_tbl ORDER BY y, x, z DESC;
+                                   QUERY PLAN                                  
 
+--------------------------------------------------------------------------------
+ Sort
+   Sort Key: y, x, z DESC
+   ->  Unique
+         ->  Index Only Scan using distinct_on_tbl_x_y_z_idx on distinct_on_tbl
+(4 rows)
+
+SELECT DISTINCT ON (y, x) x, y, z FROM distinct_on_tbl ORDER BY y, x, z DESC;
+ x | y | z  
+---+---+----
+ 0 | 0 | 22
+ 1 | 1 |  1
+ 2 | 2 |  2
+ 3 | 3 |  3
+ 4 | 4 |  4
+ 5 | 5 |  5
+ 6 | 6 |  6
+ 7 | 7 |  7
+ 8 | 8 |  8
+ 9 | 9 |  9
+(10 rows)
+
+RESET enable_incremental_sort;
+RESET enable_seqscan;
 DROP TABLE distinct_on_tbl;
diff --git a/src/test/regress/sql/select_distinct_on.sql 
b/src/test/regress/sql/select_distinct_on.sql
index 8680749e49a..e8770e7a165 100644
--- a/src/test/regress/sql/select_distinct_on.sql
+++ b/src/test/regress/sql/select_distinct_on.sql
@@ -81,4 +81,19 @@ SELECT DISTINCT ON (y, x) x, y FROM (select * from 
distinct_on_tbl order by x, z
 
 RESET enable_hashagg;
 
+-- Keep the ORDER BY suffix after reordering the DISTINCT ON keys.
+DROP INDEX distinct_on_tbl_x_y_idx;
+CREATE INDEX distinct_on_tbl_x_y_z_idx ON distinct_on_tbl (x, y, z DESC);
+INSERT INTO distinct_on_tbl VALUES (0, 0, 21), (0, 0, 22);
+ANALYZE distinct_on_tbl;
+
+SET enable_seqscan TO OFF;
+-- The index provides the full ordering needed below Unique.
+SET enable_incremental_sort TO OFF;
+EXPLAIN (COSTS OFF)
+SELECT DISTINCT ON (y, x) x, y, z FROM distinct_on_tbl ORDER BY y, x, z DESC;
+SELECT DISTINCT ON (y, x) x, y, z FROM distinct_on_tbl ORDER BY y, x, z DESC;
+RESET enable_incremental_sort;
+RESET enable_seqscan;
+
 DROP TABLE distinct_on_tbl;
-- 
2.43.0

Reply via email to