currval has not yet been defined this session, how to get multi-session sequences?

The currval will return the last value generated for the sequence within the current session. So if another session generates a new value for the sequence you still can retrieve the last value generated by YOUR session, avoiding errors.

But, to get the last generated value on any sessions, you can use the above:

SELECT last_value FROM your_sequence_name;

Be careful, if the value was used by other session with an uncommited (or aborted) transaction and you use this value as a reference, you may get an error. Even after getting this value it may already be out of date. Generally people just need the currval or even the return of setval.


This may be simpler than you think ...

My objective is to get a primary key field automatically inserted when inserting new row in the table.

Just set the default value of the column:

ALTER TABLE tbl ALTER COLUMN tbl_id SET DEFAULT nextval('my_seq'::regclass);

Or simpler yet, create the table with a serial type for primary key to begin with:

CREATE TABLE tbl(
  tbl_id serial PRIMARY KEY
 ,col1 txt
  -- more columns
);

It creates a dedicated sequence and sets the default for tbl_id automatically.

This way tbl_id is assigned the next value from the attached sequence automatically if you don't mention it in the INSERT. Works with any session, concurrent or not.

INSERT INTO tbl(col1) VALUES ('foo');

If you want the new tbl_id back to do something with it:

INSERT INTO tbl(col1) VALUES ('foo') RETURNING tbl_id;

I will give a practical answer for this matter. My database server is used by my programs and my psql terminal; so there are multiple sessions. currently I am in my psql terminal:

fooserver=> select currval('fusion_id_seq');
ERROR:  currval of sequence "fusion_id_seq" is not yet defined in this session
fooserver=> select nextval('fusion_id_seq');
 nextval 
---------
  320032
(1 row)

fooserver=> select currval('fusion_id_seq');
 currval 
---------
  320032
(1 row)

It looks that you can only see the values in your own session. This will also affect the currval of another session. This is probably related to multi-threading of the server to isolate different session. The counter (serial in psql) is a shared object. In my opinion, this session should be able to get the current value of the counter as long as the counter is properly locked to ensure only a single thread (session) can increment it (atomic operation). But I could be wrong here (not an expert on database server writer).