Re: how to get id of last insert on a serial type?

From: "Joel Burton" <joel(at)joelburton(dot)com>
To: "Robert J(dot) Sanford, Jr(dot)" <rsanford(at)trefs(dot)com>, <pgsql-general(at)postgresql(dot)org>
Subject: Re: how to get id of last insert on a serial type?
Date: 2002-05-19 13:52:07
Message-ID: JGEPJNMCKODMDHGOBKDNKELLCOAA.joel@joelburton.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

> -----Original Message-----
> From: pgsql-general-owner(at)postgresql(dot)org
> [mailto:pgsql-general-owner(at)postgresql(dot)org]On Behalf Of Robert J.
> Sanford, Jr.
> Sent: Sunday, May 19, 2002 11:33 AM
> To: pgsql-general(at)postgresql(dot)org
> Subject: Re: [GENERAL] how to get id of last insert on a serial type?
>
>
> Two quick notes/questions...
>
> 1) That would still require me to write a function for each of
> inserts to make sure that the value came back. I can't just
> do a "SELECT @@IDENTITY" and get back the last identity that
> was inserted, I have to know what sequence was used. The
> current code base that is returning the @@IDENTITY doesn't
> know anything about what was actually inserted, just that
> something was.

Am I understanding correctly -- You're getting the PK but you don't
know/care which table it's from?

If so, then, no, in PG, you need to know the sequence name to use currval()
(or nextval(), below).

> 2) Can I lock the sequence to make sure that another INSERT
> doesn't occur before I select the currval() of the sequence?

As long as you're the only user on this connection, you don't have to lock
anything to achieve this -- currval() will give you the last serial #
specific for this backend, even if there have been other inserts.

-- J.

Joel BURTON | joel(at)joelburton(dot)com | joelburton.com | aim: wjoelburton
Knowledge Management & Technology Consultant

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Susan Evans 2002-05-19 14:04:14 SSL Error
Previous Message mpls 2002-05-19 11:42:59 Re: sun solaris & postgres