pg_last_oid

(PHP 4 >= 4.2.0, PHP 5)

pg_last_oid — Returns the last row's OID

Description

stringpg_last_oid
( resource$result
)

pg_last_oid() is used to retrieve the
OID assigned to an inserted row.

OID field became an optional field from PostgreSQL 7.2 and will
not be present by default in PostgreSQL 8.1. When the
OID field is not present in a table, the programmer must use
pg_result_status() to check for successful
insertion.

To get the value of a SERIAL field in an inserted
row, it is necessary to use the PostgreSQL CURRVAL
function, naming the sequence whose last value is required. If the
name of the sequence is unknown, the pg_get_serial_sequence
PostgreSQL 8.0 function is necessary.

PostgreSQL 8.1 has a function LASTVAL that returns
the value of the most recently used sequence in the session. This avoids
the need for naming the sequence, table or column altogether.

See Also

User Contributed Notes 6 notes

The way I nuderstand it, each value is emitted by a sequence only ONCE. If you retrieve a number (say 12) from a sequence using nextval(), the sequence will advance and subsequent calls to nextval() will return further numbers (after 12) in the sequence.

This means that if you use nextval() to retrieve a value to use as a primary key, you can be guaranteed that no other calls to nextval() on that sequence will return the same value. No race conditions, no transactions required.

As pointed out on a busy site some of the above methods might actually give you an incorrect answer as another record is inserted inbetween your insert and the select. To combat this put it into a transaction and dont commit till you have done all the work