PG
PRO
24000ERRORTier 2 — Caution✅ HIGH confidence

invalid cursor state

Category: Invalid Cursor StateVersions: All Postgres versions

What this means

SQLSTATE 24000 is raised when a cursor operation is attempted on a cursor that is in an invalid or inappropriate state — for example, fetching from a closed cursor, or using a cursor that has not been opened.

Why it happens

  1. 1FETCH or CLOSE on a cursor that has already been closed
  2. 2Using a cursor after the transaction that declared it has ended
  3. 3MOVE or FETCH on a cursor that was not opened with a query

How to reproduce

Fetching from a closed cursor in PL/pgSQL.

trigger — this will ERROR
DO $
DECLARE cur CURSOR FOR SELECT * FROM employees;
BEGIN
  OPEN cur;
  CLOSE cur;
  FETCH cur INTO ...; -- invalid: cursor is closed
END $;
ERROR: cursor "cur" is not open

Fix 1: Open the cursor before fetching and check the cursor state

When managing cursors in PL/pgSQL.

fix
OPEN cur;
FETCH cur INTO rec;
-- ... use rec ...
CLOSE cur;

Why this works

Ensure cursors are opened before any FETCH or MOVE operations, and not used after closing.

Fix 2: Use FOR loops instead of explicit cursors where possible

When iterating over query results in PL/pgSQL.

fix
FOR rec IN SELECT * FROM employees LOOP
  -- process rec
END LOOP;

Why this works

FOR loops manage cursor lifecycle automatically, preventing invalid state errors.

Sources

📚 Official docs: https://www.postgresql.org/docs/current/errcodes-appendix.html

🔧 Source ref: Class 24 — Invalid Cursor State

Confidence assessment

✅ HIGH confidence

Standard SQLSTATE. Behaviour consistent across all Postgres versions.

See also

🔗 Related errors

📄 Reference pages

PL/pgSQL CursorsDECLARE CURSORFETCH
⚙️ This error reference was generated with AI assistance and reviewed for accuracy. Examples are provided to illustrate common scenarios and may not cover every case. Always test fixes in a development environment before applying to production. Spotted an error? Suggest a correction →