Re: BUG #4656: Indexes not used when comparing nextval() and currval() to integers

From: Heikki Linnakangas <heikki(dot)linnakangas(at)enterprisedb(dot)com>
To: Mathias Seiler <mathias(dot)seiler(at)gmail(dot)com>
Cc: pgsql-bugs(at)postgresql(dot)org
Subject: Re: BUG #4656: Indexes not used when comparing nextval() and currval() to integers
Date: 2009-02-16 09:37:27
Message-ID: 499933D7.2090003@enterprisedb.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-bugs

Mathias Seiler wrote:
> I'm not sure if I'm doing something terribly wrong here, but I when I
> noticed a slowdown during a large transaction I dig into the problem and
> found that when I use this prepared statement:
>
> UPDATE booking_entries SET date = ? where id =
> currval('booking_entries_id_seq'::regclass);
>
> The index over the column "id" is not used.

It's because currval and nextval are volatile functions
(http://www.postgresql.org/docs/8.3/interactive/xfunc-volatility.html).
Because of that, a lot of optimizations are disabled for them, and they
can not be used as index scan predicates. The interpretation of that
query is that you wanted to evaluate currval/nextval for all the rows in
the table, even though the UPDATE only matches some of the rows.

You can read the value returned by currval into a host language variable
and send it back as a ?.

Or you can create a wrapper function around currval that's marked as
stable instead of volatile, to hide currval's volatility. However, that
would amount to lying to the optimizer and you might get some surprising
results with more complex queries, so I wouldn't recommend it.

--
Heikki Linnakangas
EnterpriseDB http://www.enterprisedb.com

In response to

Responses

Browse pgsql-bugs by date

  From Date Subject
Next Message Brundle Fly 2009-02-16 09:39:29 BUG #4658: copy problem
Previous Message Fujii Masao 2009-02-16 07:10:48 BUG #4657: mod() makes a mistake in calculation in v8.3