24000ERRORTier 2 — Caution✅ HIGH confidenceinvalid 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
- 1FETCH or CLOSE on a cursor that has already been closed
- 2Using a cursor after the transaction that declared it has ended
- 3MOVE or FETCH on a cursor that was not opened with a query
How to reproduce
Fetching from a closed cursor in PL/pgSQL.
DO $
DECLARE cur CURSOR FOR SELECT * FROM employees;
BEGIN
OPEN cur;
CLOSE cur;
FETCH cur INTO ...; -- invalid: cursor is closed
END $;Fix 1: Open the cursor before fetching and check the cursor state
When managing cursors in PL/pgSQL.
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.
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