PostgreSQL: SELECT Last Inserted ID or Sequence Value

I have found that PostgreSQL professional are wondering about last inserted id or sequence value of PostgreSQL Tables.
You can find an N number of articles and discussion on this point.

Let me clear this topic because this is important for PostgreSQL Database Developer.

The PostgreSQL provided Sequence object and you can create a Sequence assigning SERIAL or BIGSERIAL Datatype to the columns.

You can use CURRVAL and LASTVAL to get last inserted or generated id by Sequence object.
These both are concurrently safe and behavior of Postgres Sequence is designed such a way that different session will not interfere.

But sometimes, I have found wrong ID by CURRVAL or LASTVAL because there are some additional trigger rule written like, when you insert one row in X table, some other row also require to insert in Y table using an INSERT Trigger.

When some extra insertion or load of insertion is going on by different source, some time LASTVAL and CURRVAL returns wrong ID. This is very rare situation, but still risk is there.

The best solution is PostgreSQL INSERT RETURNING:
Using INSERT RETURNING, you can select last inserted id for that only INSERT at the time of insertion.
Below is a small demo:

First, create a sample table:

Now Insertion with RETURNING a last inserted value:

After executing this INSERT statement, you will get the last inserted ID.
My Suggestion is to use RETURNING instead of CURRVAL and LASTVAL.

Anvesh Patel

Leave a Reply

2 Comments on "PostgreSQL: SELECT Last Inserted ID or Sequence Value"

Notify of
avatar
Sort by:   newest | oldest | most voted
Felipa
Guest

Thanks in support of sharing such a fastidious thinking, piece of writing
is fastidious, thats why i hve read it completely

Ashvin
Guest

You are a very capable individual!
God bless you !

wpDiscuz