Re: Sequences in transaction context

From: Doug McNaught <doug(at)wireboard(dot)com>
To: "Erik Pearson" <erik(at)cariboulake(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Sequences in transaction context
Date: 2001-06-06 03:14:06
Message-ID: m3g0dewb9d.fsf@belphigor.mcnaught.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

"Erik Pearson" <erik(at)cariboulake(dot)com> writes:

> I searched through mailing list archives but was unable to find full
> coverage of this question -- my apologies if this is a reposted question.
>
> As in the FAQ, I am trying to retrieve the value of a sequence value from a
> newly inserted row. So, first I call something like:
>
> insert into foobar (foo, bar)
> values (nextval('foobar_foo_seq'), 'whatever');
>
> Then, I want to retrieve the value that generated from the sequence and
> inserted into the table, so I use a call to currval:
>
> insert into foobar_rel_table(foo_fk, baz)
> values (currval('foobar_foo_seq', 'something else');
>
> This is (one of the methods that is) prescribed in the FAQ. However, I'm
> concerned that another transaction attempting to insert into the same table
> might make a call to nextval('foobar_foo_seq') between the two operations
> above. This would mean that my second statement would use the wrong value
> from the sequence.

This does not happen. I just tested it:

[doug(at)shaggy doug]$ createdb foo
CREATE DATABASE
[doug(at)shaggy doug]$ psql foo
Welcome to psql, the PostgreSQL interactive terminal.

Type: \copyright for distribution terms
\h for help with SQL commands
\? for help on internal slash commands
\g or terminate with semicolon to execute query
\q to quit

foo=# create sequence foo_seq;
CREATE
foo=# select nextval('foo_seq');
nextval
---------
1
(1 row)

foo=# select currval('foo_seq');
currval
---------
1
(1 row)

At this point, in another window, I do:

foo=# select nextval('foo_seq');
nextval
---------
2
(1 row)

Back to the first window:

foo=# select currval('foo_seq');
currval
---------
1
(1 row)

Are you not seeing this behavior? Since you mention the FAQ, question
4.16.3 addresses this very issue in very clear language.

Welcome to MVCC...

-Doug
--
The rain man gave me two cures; he said jump right in,
The first was Texas medicine--the second was just railroad gin,
And like a fool I mixed them, and it strangled up my mind,
Now people just get uglier, and I got no sense of time... --Dylan

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Stephan Szabo 2001-06-06 03:16:36 Re: Sequences in transaction context
Previous Message Trond Eivind =?iso-8859-1?q?Glomsr=F8d?= 2001-06-06 03:03:12 Re: ORDER BY Problem