Reordering DISTINCT keys to match input path's pathkeys - Mailing list pgsql-hackers

From Richard Guo
Subject Reordering DISTINCT keys to match input path's pathkeys
Date
Msg-id CAMbWs48dR26cCcX0f=8bja2JKQPcU64136kHk=xekHT9xschiQ@mail.gmail.com
Whole thread Raw
Responses Re: Reordering DISTINCT keys to match input path's pathkeys
Re: Reordering DISTINCT keys to match input path's pathkeys
List pgsql-hackers
Similar to what we did to GROUP BY keys in 0452b461bc, I think we can do
the same to DISTINCT keys, i.e. reordering DISTINCT keys to match input
path's pathkeys, which can help reduce cost by avoiding unnecessary
re-sort, or allowing us to use incremental-sort to save efforts.  For
instance,

create table t (a int, b int);
create index on t (a, b);

explain (costs off) select distinct b, a from t limit 10;
                    QUERY PLAN
--------------------------------------------------
 Limit
   ->  Unique
         ->  Index Only Scan using t_a_b_idx on t
(3 rows)


Please note that the parser has ensured that the DISTINCT pathkeys
matches the order of ORDER BY clauses.  So there is no need to do this
part again.

In principle, we can perform such reordering for DISTINCT ON too, but we
need to make sure that the resulting pathkeys matches initial ORDER BY
keys, which seems not trivial.  So it doesn't seem worth the effort.

Attached is a patch for this optimization.  Any thoughts?

Thanks
Richard
Attachment

pgsql-hackers by date:

Previous
From: Michael Paquier
Date:
Subject: Re: Test slots invalidations in 035_standby_logical_decoding.pl only if dead rows are removed
Next
From: Fujii Masao
Date:
Subject: Re: Network failure may prevent promotion