There is no standard way to do this (just as there is no standard way to create auto-increment identifiers). Here are two ways to do this in PostgreSQL. Suppose this is your table:
CREATE TABLE mytable ( id SERIAL PRIMARY KEY, lastname VARCHAR NOT NULL, firstname VARCHAR );
You can do this in two operations if they are consecutive statements in the same connection (this will be safe in PHP with a connection pool, since PHP does not return the connection to the pool until your script is done):
INSERT INTO mytable (lastname, firstname) VALUES ('Washington', 'George'); SELECT lastval();
lastval () gives you the last automatically generated sequence value used in the current connection.
Another way is to use the PostgreSQL RETURNING clause in INSERT :
INSERT INTO mytable (lastname) VALUES ('Cher') RETURNING id;
This form returns the result set in the same way as the SELECT statement, and is also convenient for returning any calculated default value.
Neall Sep 05 '08 at 13:16 2008-09-05 13:16
source share