Reordering DISTINCT keys to match input path's pathkeys
authorRichard Guo <rguo@postgresql.org>
Tue, 26 Nov 2024 00:25:18 +0000 (09:25 +0900)
committerRichard Guo <rguo@postgresql.org>
Tue, 26 Nov 2024 00:25:18 +0000 (09:25 +0900)
commita8ccf4e93a7eeaae66007bbf78cf9183ceb1b371
tree8ef9b2d3f02d8f51de10ce95531de962245a451d
parent5b8728cd7f9d3d93b6ff9b48887084fdf0a46e4f
Reordering DISTINCT keys to match input path's pathkeys

The ordering of DISTINCT items is semantically insignificant, so we
can reorder them as needed.  In fact, in the parser, we absorb the
sorting semantics of the sortClause as much as possible into the
distinctClause, ensuring that one clause is a prefix of the other.
This can help avoid a possible need to re-sort.

In this commit, we attempt to adjust the DISTINCT keys to match the
input path's pathkeys.  This can likewise help avoid re-sorting, or
allow us to use incremental-sort to save efforts.

For DISTINCT ON expressions, the parser already ensures that they
match the initial ORDER BY expressions.  When reordering the DISTINCT
keys, we must ensure that the resulting pathkey list matches the
initial distinctClause pathkeys.

This introduces a new GUC, enable_distinct_reordering, which allows
the optimization to be disabled if needed.

Author: Richard Guo
Reviewed-by: Andrei Lepikhov
Discussion: https://postgr.es/m/CAMbWs48dR26cCcX0f=8bja2JKQPcU64136kHk=xekHT9xschiQ@mail.gmail.com
doc/src/sgml/config.sgml
src/backend/optimizer/path/pathkeys.c
src/backend/optimizer/plan/planner.c
src/backend/utils/misc/guc_tables.c
src/backend/utils/misc/postgresql.conf.sample
src/include/optimizer/optimizer.h
src/test/regress/expected/select_distinct.out
src/test/regress/expected/select_distinct_on.out
src/test/regress/expected/sysviews.out
src/test/regress/sql/select_distinct.sql
src/test/regress/sql/select_distinct_on.sql