Search Postgresql Archives

Getting ID of last-inserted row

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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

-- 
Sent via pgsql-general mailing list (pgsql-general@xxxxxxxxxxxxxx)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-general

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[Index of Archives]     [Postgresql Jobs]     [Postgresql Admin]     [Postgresql Performance]     [Linux Clusters]     [PHP Home]     [PHP on Windows]     [Kernel Newbies]     [PHP Classes]     [PHP Books]     [PHP Databases]     [Postgresql & PHP]     [Yosemite]
  Powered by Linux