currval not defined 🐘 PostgreSQL

ERROR: currval of sequence "x" is not yet defined in this session

currval() was called before nextval() in the same session.

Seen on: PostgreSQL

Meaning

currval returns the value most recently obtained by nextval in your session. With connection pools, calls can land on different connections.

Common causes

  • currval before any insert in the session
  • Pooled connections splitting nextval and currval

⚡ Quick fix

  1. Use INSERT … RETURNING id instead
  2. Or lastval() right after the insert on the same connection

Detailed fix by platform

PostgreSQL

  1. INSERT INTO orders (user_id) VALUES ($1) RETURNING id;

How to diagnose

  1. Session — Same connection for insert and currval?
  2. Recent change — Did it start after a deploy, upgrade, or configuration change? Compare with the last working version.

🧠 Still stuck? Analyze your error

Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.