While reviewing [1], I visited other places where sorting is needed, and have some findings.
In add_paths_with_pathkeys_for_rel, we do not try incremental sort atop of the epq_path, which I think we can do. I'm not sure how useful this is in real world since the epq_path is used only for EPQ checks, but it seems doing that doesn't cost too much. In create_ordered_paths, we are trying to sort the cheapest partial path and incremental sort on any partial paths with presorted keys, and then use Gather Merge. If the cheapest partial path is not completely sorted but happens to have presorted keys, we would create a full sort path and an incremental sort path on it. I think this is not what we want. We are supposed to only create an incremental sort path if there are presorted keys. In gather_grouping_paths, we have the same issue. In addition, for the incremental sort paths created atop partial paths, we neglect to calculate 'total_groups' before we use it in create_gather_merge_path. [1] https://www.postgresql.org/message-id/flat/CAApHDvo8Lz2H%3D42urBbfP65LTcEUOh288MT7DsG2_EWtW1AXHQ%40mail.gmail.com Thanks Richard
v1-0003-Revise-how-we-sort-partial-paths-in-gather_grouping_paths.patch
Description: Binary data
v1-0002-Revise-how-we-sort-partial-paths-in-create_ordered_paths.patch
Description: Binary data
v1-0001-postgres_fdw-Allow-incremental-sort-atop-of-the-epq_path.patch
Description: Binary data