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:
CREATE TABLE tbl_TestReturnID
,Name CHARACTER VARYING
,Address CHARACTER VARYING
,CONSTRAINT pk_tbl_TestReturnID_Rno PRIMARY KEY(Rno)
Now Insertion with RETURNING a last inserted value:
INSERT INTO tbl_TestReturnID (Name,Address)
VALUES ('Anvesh','Hyderabad') RETURNING Rno;
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 dbrnd.com, 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.