This article is half-done without your Comment! *** Please share your thoughts via Comment ***
I found that PostgreSQL professionals 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 describe this topic in my words, because this is important for PostgreSQL Database Developers.
The PostgreSQL provideds Sequence object and you can create a Sequence by assigning SERIAL or BIGSERIAL Datatype to the columns.
You can use CURRVAL and LASTVAL to get the last inserted or generated ID by the Sequence object.
These both are concurrently safe, and behaviour of Postgres Sequence is designed such a way that different sessions will not interfere with each other.
But sometimes, I found the wrong ID by CURRVAL or LASTVAL because there is 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 the different sources, LASTVAL and CURRVAL return the wrong ID. This is the very rare situation, but still, the 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:
Create a sample table:
CREATE TABLE tbl_TestReturnID
,Name CHARACTER VARYING
,Address CHARACTER VARYING
,CONSTRAINT pk_tbl_TestReturnID_Rno PRIMARY KEY(Rno)
Insertion with RETURNING a last inserted value:
INSERT INTO tbl_TestReturnID (Name,Address)
VALUES ('Anvesh','Hyderabad') RETURNING Rno;
After executing above INSERT statement, you will get the last inserted ID.
My Suggestion is to use RETURNING instead of CURRVAL and LASTVAL.