Re: currval() within one statement

From: hubert depesz lubaczewski <depesz(at)depesz(dot)com>
To: silly_sad <sad(at)bankir(dot)ru>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: currval() within one statement
Date: 2008-01-22 11:27:54
Message-ID: 20080122112753.GA13184@depesz.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On Tue, Jan 22, 2008 at 10:16:30AM +0300, silly_sad wrote:
> INSERT INTO ttt (a,b) SELECT currval('ttt_id_seq'), 'const' FROM ttt2;
> Where the trigger before insert on ttt is defined and this trigger calls
> nextval('ttt_id_seq').
> I was surprised having different values of currval() in ttt.a
> Is this the normal behavior ? Where is it described ?

currval is volatile function:
select provolatile from pg_proc where proname = 'currval';
it means it is called for every row separately.
and since it is inserted, it's evaluation is (i guess):

get 1 row from select
insert
get next row from select
insert
...

which means, that the sequence gets updated in mean time (by trigger).

if you want to have the same currval, i would suggest to do:

INSERT INTO ttt (a,b) SELECT (select currval('ttt_id_seq')), 'const' FROM ttt2;
(which should work).

or (and this would be definitely the best way) seriously rethink the
schema.

depesz

--
quicksil1er: "postgres is excellent, but like any DB it requires a
highly paid DBA. here's my CV!" :)
http://www.depesz.com/ - blog dla ciebie (i moje CV)

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Richard Huxton 2008-01-22 12:18:47 Re: currval() within one statement
Previous Message silly_sad 2008-01-22 11:27:29 Re: currval() within one statement