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.

Please share your ideas and opinions about this topic with me, your contribution will add true value to this topic.
If anyone has doubts on this topic then please do let me know by leaving comments or send me an email.

If you like this post, then please share it with others.
Please follow, I will share my experience towards the success of Database Research and Development Activity.

I put up a post every day, please keep reading and learning.
Discover Yourself, Happy Blogging !
Anvesh M. Patel.

More from

Leave a Reply

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

Notify of

Sort by:   newest | oldest | most voted
10 months 21 days ago

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

5 months 29 days ago

You are a very capable individual!
God bless you !