Re: currval() within one statement - Mailing list pgsql-sql

From hubert depesz lubaczewski
Subject Re: currval() within one statement
Date
Msg-id 20080122112753.GA13184@depesz.com
Whole thread Raw
In response to currval() within one statement  (silly_sad <sad@bankir.ru>)
List 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)


pgsql-sql by date:

Previous
From: silly_sad
Date:
Subject: Re: currval() within one statement
Next
From: Richard Huxton
Date:
Subject: Re: currval() within one statement