ERROR: currval of sequence “SEQUENCE_NAME” is not yet defined in this session

In PostgreSQL, when trying to get the current value of a sequence, the following errors occur:

select currval('SEQUENCE_NAME');

ERROR:  currval of sequence "SEQUENCE_NAME" is not yet defined in this session
SQL state: 55000

SOLUTION

Query PG_SEQUENCES to get the last value of sequences.

=> \d pg_sequences
              View "pg_catalog.pg_sequences"
    Column     |  Type   | Collation | Nullable | Default
---------------+---------+-----------+----------+---------
 schemaname    | name    |           |          |
 sequencename  | name    |           |          |
 sequenceowner | name    |           |          |
 data_type     | regtype |           |          |
 start_value   | bigint  |           |          |
 min_value     | bigint  |           |          |
 max_value     | bigint  |           |          |
 increment_by  | bigint  |           |          |
 cycle         | boolean |           |          |
 cache_size    | bigint  |           |          |
 last_value    | bigint  |           |          |

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.