currval lastval Session Sequence State
currval and lastval read session-local sequence state: currval needs that sequence drawn via nextval in this session, lastval needs any nextval at all.
Code
CREATE SEQUENCE ticket_no_seq;
-- 本会话先取一次号,序列状态才有值
SELECT nextval('ticket_no_seq') AS first_draw;
-- currval:本会话对该序列最近一次 nextval 的值
SELECT currval('ticket_no_seq') AS seq_current;
SELECT lastval() AS seq_last; -- lastval:本会话最近用过的序列的值
-- 其他会话并发取号不影响本会话的 currval:会话局部语义
SELECT nextval('ticket_no_seq') AS second_draw;
SELECT currval('ticket_no_seq') AS updated_current;
-- 错误场景(注释掉以免中断脚本):
-- SELECT currval('ticket_no_seq') 之前若本会话从未 nextval 该序列:
-- ERROR: currval of sequence "..." is not yet defined in this session
-- 空会话直接调 lastval:
-- ERROR: lastval is not yet defined in this sessionHow it works
What runs here is SELECT / CREATE.
Why the two reads differ
currval is scoped to one sequence: it answers “what did this session last draw from ticket_no_seq”, and PostgreSQL raises ERROR: currval of sequence "..." is not yet defined in this session when the session never called nextval on that sequence. lastval is session-local but sequence-agnostic: it returns the value of whichever sequence this session touched most recently, and an untouched session gets ERROR: lastval is not yet defined in this session. Both reads never look at other connections — concurrent sessions drawing from the same sequence do not change what these calls return, which is why updated_current reflects second_draw from this session and nothing else.
The core lines, annotated
SELECT lastval() AS seq_last; -- lastval:本会话最近用过的序列的值
SELECT currval('ticket_no_seq') AS updated_current;
SELECT currval('ticket_no_seq') AS seq_current;
Interactive Tools for This Topic
Report a problem with this exampleOpens a pre-filled issue on GitHub.