24000
PostgreSQLERRORNotableInvalid Cursor StateHIGH confidence

invalid cursor state

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
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 $;

expected output

ERROR:  cursor "cur" is not open

Fix 1

Open the cursor before fetching and check the cursor state

WHEN When managing cursors in PL/pgSQL.

Open the cursor before fetching and check the cursor state
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 When iterating over query results in PL/pgSQL.

Use FOR loops instead of explicit cursors where possible
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 documentation ↗

Class 24 — Invalid Cursor State

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All PostgreSQL errors