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.