Re: Getting ID of last-inserted row

From: Raymond O'Donnell <rod(at)iol(dot)ie>
To: "A(dot) Kretschmer" <andreas(dot)kretschmer(at)schollglas(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Getting ID of last-inserted row
Date: 2009-05-20 10:23:38
Message-ID: 4A13DA29.5070601@iol.ie
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On 20/05/2009 11:17, A. Kretschmer wrote:
> In response to David :
>> Hi there.
>>
>> I never found an adequate (simple and efficient) method for getting
>> the primary key ID of the just-inserted row, and usually used
>> transactions and "select last value, ordered by id"-type queries to
>> get the last id value, or other ugly logic.
>
> use currval() instead, see
> http://www.postgresql.org/docs/current/static/functions-sequence.html

Also, you can do insert....returning... (as of version 8.2, I think):

INSERT INTO clients (id, name)
VALUES (nextval('clients_id_seq'), 'John Smith')
RETURNING id;

Ray.

------------------------------------------------------------------
Raymond O'Donnell, Director of Music, Galway Cathedral, Ireland
rod(at)iol(dot)ie
Galway Cathedral Recitals: http://www.galwaycathedral.org/recitals
------------------------------------------------------------------

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Peter Geoghegan 2009-05-20 10:28:49 Suggested way of associating PG user metadata with record
Previous Message A. Kretschmer 2009-05-20 10:17:23 Re: Getting ID of last-inserted row