PostgreSQL Error 24000: Invalid Cursor State Fix
In this article
PostgreSQL error 24000 (invalid_cursor_state) means your session tried to fetch from, move, or close a cursor that is not currently open in that session. The fix is to open the cursor in the same transaction and session where you use it, fetch before you close it, and make sure no earlier error or COMMIT already destroyed it. In practice: wrap DECLARE, FETCH, and CLOSE in one transaction block, check that the cursor name matches exactly, and look for a prior failed statement that aborted the transaction.
What You'll Need
- Access to the PostgreSQL server with a role that can run the failing query (psql, pgAdmin, or your application's database client).
- The exact SQL or application code that produces the error, including the cursor name and the surrounding transaction statements.
- The PostgreSQL server log, if available, to see whether an earlier error aborted the transaction.
- A non-production database or schema where you can reproduce the problem safely.
Step-by-Step
- Reproduce the error in psql. Connect to the same database with the same role and run the statements in the same order your application runs them. The error text usually includes the cursor name, for example
cursor "my_cursor" does not existorinvalid cursor state. Note which statement triggers it: FETCH, MOVE, CLOSE, or an application call that wraps one of those. - Check that the cursor was declared in the current transaction. In PostgreSQL, a cursor declared without
WITH HOLDexists only until the end of the transaction. If your code issuesCOMMITor the connection pool starts a new transaction between DECLARE and FETCH, the cursor is gone. Put DECLARE, all FETCH calls, and CLOSE inside oneBEGIN ... COMMITblock, or declare the cursorWITH HOLDif you genuinely need it to survive a commit. - Confirm the cursor name matches exactly. Cursor names are identifiers; unquoted names are folded to lowercase, while quoted names keep their case. A cursor declared as
DECLARE "MyCursor" CURSOR FOR ...must be fetched asFETCH "MyCursor". Check for typos, stray spaces, and differences between the name your application builds and the name it later uses. - Look for an earlier error that aborted the transaction. Once a statement fails inside a transaction, PostgreSQL marks the transaction as aborted and every later command, including FETCH, returns an error until you
ROLLBACK. RunROLLBACK;, then re-run the sequence and watch for the first error, not the cursor error that follows it. - Verify the cursor is still open before fetching. If your code may close the cursor early (for example in a
finallyblock that runs on an exception), guard the FETCH or check your application's cursor state. In psql you can querypg_cursorsto see which cursors are open in the current session:SELECT name, statement, is_holdable FROM pg_cursors;. If the cursor is not listed, it is not open. - Check transaction handling in your driver or ORM. Many drivers and ORMs run each statement in its own implicit transaction unless you explicitly begin one. That breaks server-side cursors. Use the driver's transaction API, or configure the connection so that DECLARE and FETCH share a transaction. In autocommit mode, server-side cursors will not work as expected.
- Check for connection pooling or session changes. A cursor belongs to one session. If a pool hands your FETCH to a different connection than the one that ran DECLARE, the cursor does not exist there. Either pin the whole cursor operation to one connection, or avoid server-side cursors in pooled, stateless request paths and fetch rows in a single query instead.
- Re-test with the corrected sequence. Run the full block again in psql, then in your application. Confirm that FETCH returns rows, that CLOSE succeeds, and that COMMIT completes without error. If the application still fails, compare the exact SQL it sends (enable statement logging temporarily) with the psql version that worked.
Common Mistakes
- Declaring a cursor and then committing before fetching. Without
WITH HOLD, the cursor is closed at commit. - Fetching after CLOSE. Once closed, the cursor cannot be reused; declare a new one.
- Ignoring the first error in a transaction. The cursor error is often a side effect of an earlier failure that aborted the transaction.
- Assuming cursor names are case-insensitive in all cases. Quoted identifiers preserve case.
- Using server-side cursors through a connection pool without pinning the connection.
- Mixing up client-side result sets (the driver buffering rows) with server-side cursors (DECLARE/FETCH). Only the latter produces this error.
Tips
- Use
WITH HOLDonly when you truly need a cursor to outlive a transaction; held cursors consume resources until closed or the session ends. - Always close cursors explicitly with
CLOSE cursor_name;when you are done, especially in long-lived sessions. - Keep cursor blocks short. Long-running transactions that hold cursors open can block vacuum and cause bloat.
- Log the exact SQL your application sends during debugging; the mismatch between what you think it sends and what it actually sends is often the cause.
- Prefer a single query with LIMIT/OFFSET or keyset pagination for simple paging instead of server-side cursors, unless you need row-by-row processing.
Troubleshooting
If the error persists after the steps above, work through these checks in order.
- Confirm the transaction is not aborted. Run
ROLLBACK;and retry the block from the start. If the error disappears, an earlier statement was failing silently in your application code. - Check the server log. Look for the first ERROR in the session, not the cursor error. The log shows the statement that actually failed.
- Test with a minimal script. In psql, run
BEGIN; DECLARE c CURSOR FOR SELECT 1; FETCH 1 FROM c; CLOSE c; COMMIT;. If that works, the problem is in your application's transaction or connection handling, not in PostgreSQL itself. - Inspect open cursors.
SELECT * FROM pg_cursors;shows cursors in the current session. If yours is missing, it was never declared on this connection or was already closed. - Check driver settings. Some drivers have options that control whether cursors are held open or closed after commit; review your driver's documentation for cursor and transaction behavior.
- Rule out pooling. Temporarily set the pool size to one connection and retry. If the error goes away, the pool was switching sessions between DECLARE and FETCH.
Frequently Asked Questions
What does PostgreSQL error 24000 mean?
It is the SQLSTATE for invalid cursor state: a cursor operation was attempted on a cursor that is not open in the current session, usually because it was never declared there, was already closed, or the transaction ended.
Does COMMIT close cursors?
Yes, for cursors declared without WITH HOLD. They are closed at the end of the transaction. Cursors declared WITH HOLD remain available after commit until closed or the session ends.
Why does my cursor work in psql but fail in my application?
Most often because the application runs each statement in its own transaction, or a connection pool uses a different connection for FETCH than for DECLARE. Both break server-side cursors.
Can I reuse a cursor after CLOSE?
No. After CLOSE the cursor no longer exists. Declare a new cursor with the same name if you need to run the query again.
How do I see which cursors are open?
Query pg_cursors in the current session. It lists open cursors, their defining statement, and whether they are holdable.
Is error 24000 dangerous to my data?
No. It is a state error, not corruption. Fixing the transaction or cursor sequence resolves it without data loss.