Getting ID of last-inserted row - Mailing list pgsql-general

From David
Subject Getting ID of last-inserted row
Date
Msg-id 18c1e6480905200250nba56fcct1ee21ceeaa82df19@mail.gmail.com
Whole thread Raw
Responses Re: Getting ID of last-inserted row  ("A. Kretschmer" <andreas.kretschmer@schollglas.com>)
List pgsql-general
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.

That was until I found how SQLalchemy[1] handles it for PostgreSQL.
What they do is:

1) First, get the next value from the sequence, eg:

SELECT nextval('clients_id_seq');

2) Then, run an insert statement, where the retrieved value is
explicitly given, rather than automatically assigned, eg:

INSERT INTO clients (id, name) VALUES (12345, 'John Smith');

(Where 12345 is the id retrieved from the previous query).

I wanted to add this info to the wiki[2], but there doesn't seem to be
a way to sign up.

Anyway, I thought that other people might find this info useful.

David.

[1] http://www.sqlalchemy.org/
[2] http://wiki.postgresql.org/wiki/Main_Page

pgsql-general by date:

Previous
From: Grzegorz Jaśkiewicz
Date:
Subject: Re: Can I pause the pg_dump or pg_restore
Next
From: David
Date:
Subject: Re: Can I pause the pg_dump or pg_restore