Re: Redundant Unique plan node for table with a unique index

From: David Rowley <dgrowleyml(at)gmail(dot)com>
To: Damir Belyalov <dam(dot)bel07(at)gmail(dot)com>
Cc: PostgreSQL Hackers <pgsql-hackers(at)postgresql(dot)org>, a(dot)lepikhov(at)postgrespro(dot)ru
Subject: Re: Redundant Unique plan node for table with a unique index
Date: 2023-09-13 23:39:05
Message-ID: CAApHDvpD7fFk5O3aaACiZ+kNDaXs0+CP-9B8Ri7ZoFwXq4P_xA@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

On Thu, 14 Sept 2023 at 02:28, Damir Belyalov <dam(dot)bel07(at)gmail(dot)com> wrote:
> create table a (n int);
> insert into a (n) select x from generate_series(1, 140000) as g(x);
> create unique index on a (n);
> explain select distinct n from a;
> QUERY PLAN
> ------------------------------------------------------------------------------------
> Unique (cost=0.42..6478.42 rows=140000 width=4)
> -> Index Only Scan using a_n_idx on a (cost=0.42..6128.42 rows=140000 width=4)
> (2 rows)
>
>
> We can see that Unique node is redundant for this case. So I implemented a simple patch that removes Unique node from the plan.

I don't think this is a good way to do this. The method you're using
only supports this optimisation when querying a table directly. If
there were subqueries, joins, etc then it wouldn't work as there are
no unique indexes. You should probably have a look at [1] to see
further details of an alternative method without the said limitations.

David

[1] https://postgr.es/m/flat/CAKU4AWqZvSyxroHkbpiHSCEAY2C41dG7VWs%3Dc188KKznSK_2Zg%40mail.gmail.com

In response to

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message David Rowley 2023-09-13 23:57:11 Re: Surely this code in setrefs.c is wrong?
Previous Message Imseih (AWS), Sami 2023-09-13 23:09:19 Re: Jumble the CALL command in pg_stat_statements