From: | David <wizzardx(at)gmail(dot)com> |
---|---|
To: | pgsql-general(at)postgresql(dot)org |
Subject: | Getting ID of last-inserted row |
Date: | 2009-05-20 09:50:07 |
Message-ID: | 18c1e6480905200250nba56fcct1ee21ceeaa82df19@mail.gmail.com |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | 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
From | Date | Subject | |
---|---|---|---|
Next Message | David | 2009-05-20 09:54:42 | Re: Can I pause the pg_dump or pg_restore |
Previous Message | Grzegorz Jaśkiewicz | 2009-05-20 09:42:30 | Re: Can I pause the pg_dump or pg_restore |