Take the 2-minute tour ×

Ideally I'd like to be able to do something like:

id_of_new_row = cursor.lastrowid()

in which I get the id of the newly created or modified row. But this isn't available through psycopg2. Alternatively, I've tried this:

id_of_new_row = cursor.execute('INSERT INTO this_table (value1, value2, value3) VALUES (%s, %s, %s) RETURNING id', (some_value1, some_value2, some_value3))

which doesn't work, probably because it won't know the id until after the commit is made...


share|improve this question
What kind of ID you're trying to get - OID or the value of a field declared SERIAL? –  Milen A. Radev Jan 27 '10 at 0:29
I don't know. I'm new. This is a django project, and django sets up the postgres database with syncdb based on my models. I'm not sure if django declares OID during table creation automatically. I need the primary key of each row, which is auto-generated as "id" by django, unless otherwise specified. I'll do some reading. –  Cody Jan 27 '10 at 16:10
add comment

2 Answers

up vote 15 down vote accepted

Sure it will, it'll know the ID as soon as the command finishes, that's how RETURNING is implemented. You need to actually fetch it though, so something like:

cursor.execute("INSERT INTO .... RETURNING id")
id_of_new_row = cursor.fetchone()[0]

should work in your scenario.

share|improve this answer
Amazing. Thanks! –  Cody Jan 27 '10 at 16:11
add comment

RETURNING works on Postgresql >= 8.2

share|improve this answer
add comment

Your Answer


