Re: next integer in serial key

From: Oliver Elphick <olly(at)lfix(dot)co(dot)uk>
To: terry(at)ashtonwoodshomes(dot)com
Cc: 'Kenneth Gonsalves' <lawgon(at)thenilgiris(dot)com>, "Postgresql Sql Group (E-mail)" <pgsql-sql(at)postgresql(dot)org>
Subject: Re: next integer in serial key
Date: 2004-07-22 12:15:26
Message-ID: 1090498526.5446.9.camel@braydb
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On Thu, 2004-07-22 at 12:48, terry(at)ashtonwoodshomes(dot)com wrote:
> Actually it does work, call nextval to get your next value, then call
> your INSERT statement,
> explicitly giving said value for the serial column. Then you can
> proceed with using said value in
> the INSERT statement of the related inserts with foreign keys to it.
>
> Alternatively, you can do:
> INSERT (accepting the default)
> then SELECT currval(the_sequence_object);
> then <extra inserts of related foreign key records>
>
> NOTE: 2nd method assumes that nobody else called nextval() on the
> sequence between when you did the
> insert and when you did the select currval(). Note that being inside
> a transaction is NOT
> sufficient, you need an explicit lock on the sequence. I do not
> recommend the 2nd method, too much
> can go wrong.

This last paragraph is wrong and irrelevant. It is a point which for
some reason is continually being misunderstood.

currval() *always* returns the last value generated for the sequence in
the *current session*. It is specifically designed to do what you are
suggesting without any conflict with other sessions. There is *never*
any risk of getting a value that nextval() returned to some other user's
session.

The downside is that it operates outside the transaction and therefore
cannot be rolled back. It is also necessary to run nextval() in the
session (either explicitly or by letting a serial column take its
default) before you can use currval() on the sequence.

Oliver Elphick

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Karsten Hilbert 2004-07-22 12:20:40 Re: surrogate key or not?
Previous Message Kenneth Gonsalves 2004-07-22 11:51:30 Re: next integer in serial key