currval
PG 7.4+→ bigintReturns the most recent value returned by nextval for the given sequence in the current session. Raises an error if nextval has not been called in this session.
Signature
currval ( regclass ) → bigintParameters
| Parameter | Type | Description |
|---|---|---|
| sequence_name | regclass | Name of the sequence |
Examples
SELECT nextval('my_seq'); SELECT currval('my_seq');Both return the same valueINSERT INTO orders (id) VALUES (nextval('order_seq')); SELECT currval('order_seq') AS new_order_id;Retrieve the just-inserted ID-- Safe pattern: call nextval once, use currval as many times as needed
SELECT nextval('invoice_seq');
INSERT INTO invoices (id, notes) VALUES (currval('invoice_seq'), 'draft');
INSERT INTO invoice_audit (invoice_id, event) VALUES (currval('invoice_seq'), 'created');currval returns the same value for both inserts — no extra sequence advance-- Demonstrate the session scope: currval is invisible to other connections
-- Session A:
SELECT nextval('my_seq'); -- returns 42
-- Session B (different connection):
SELECT currval('my_seq'); -- ERROR: currval of sequence not yet defined in this sessioncurrval is strictly per-session — other sessions cannot see itCalling `currval('seq')` without having first called `nextval('seq')` in the same session raises a runtime error: `ERROR: currval of sequence "seq" is not yet defined in this session`. A common trigger for this bug is code that tries to retrieve the last inserted ID using `currval` in a fresh connection or after a connection pool recycles the connection, where the prior `nextval` was executed on a different session.
✓ Instead: Always call `nextval` in the same session before relying on `currval`. Better still, use `INSERT ... RETURNING id` which eliminates the dependency on `currval` entirely and is immune to session lifecycle issues.
For tables with `SERIAL` or `GENERATED ... AS IDENTITY`, prefer `INSERT ... RETURNING id` to get the new ID — it's cleaner and works correctly even with triggers that modify the row.
INSERT INTO orders (amount) VALUES (100) RETURNING id;Returns the new ID without needing currval