Re: Last ID

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: "Brett W(dot) McCoy" <bmccoy(at)chapelperilous(dot)net>
Cc: Catalin CIOCOIU <catalin(dot)ciocoiu(at)inpg(dot)fr>, "pgsql-novice(at)postgresql(dot)org" <pgsql-novice(at)postgresql(dot)org>
Subject: Re: Last ID
Date: 2001-03-02 17:48:35
Message-ID: 4053.983555315@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-novice

"Brett W. McCoy" <bmccoy(at)chapelperilous(dot)net> writes:
> On Fri, 2 Mar 2001, Catalin CIOCOIU wrote:
>> How can I get Last ID inserted ???

> currval('<seq name>') is the way to get the value that was last inserted
> into the database. However, there is no guarantee, in a multiuser
> environment, that the value you got was the value you actually used.

Quite a few people don't seem to understand how currval() and nextval()
work.

1. nextval() advances the sequence object, generating a new value that
will not be the same as any other nextval() call returns, in either
this backend or any other one.

2. currval() gives the last value generated by a nextval() *IN THIS
BACKEND*. It is undefined until the current backend has done at
least one nextval() on the sequence object.

There is no "multiuser risk" from either one: in particular, currval()
will give you the value you last generated, regardless of what other
backends may be doing.

> You can also user last_value in an SQL statement, but you still have
> the problem of having multiple backends generating sequence values.

Yes, looking directly at the sequence's last_value does open up race
conditions.

regards, tom lane

In response to

  • Re: Last ID at 2001-03-02 16:33:34 from Brett W. McCoy

Responses

Browse pgsql-novice by date

  From Date Subject
Next Message Brett W. McCoy 2001-03-02 18:23:45 Re: Last ID
Previous Message Catalin CIOCOIU 2001-03-02 17:20:05 Re: Last ID