PostgreSQL Error 42P03: Duplicate Cursor Fix
In this article
PostgreSQL error 42P03 (duplicate_cursor) means you tried to declare a cursor with a name that is already in use in the current session. The fix is to either close the existing cursor before declaring a new one with the same name, or use a unique name for each cursor. This error is session-scoped: it only occurs when a cursor with that exact name is still open in the same database connection. It is not a server-wide condition, so two different sessions can use the same cursor name without conflict.
What You'll Need
- Access to a PostgreSQL client (psql, pgAdmin, DBeaver, or your application's database driver) and permission to run SQL in the session where the error occurs.
- The SQL statement or stored procedure that declares the cursor, so you can inspect and adjust the cursor name or lifecycle.
- Basic familiarity with transaction blocks: cursors declared without
WITH HOLDare closed automatically at the end of the transaction that created them.
Step-by-Step
- Reproduce the error and note the cursor name. Run the failing statement again and read the full message. PostgreSQL reports
ERROR: cursor "name" already existswith SQLSTATE 42P03. Write down the exact cursor name; it is case-sensitive unless you used unquoted identifiers, which PostgreSQL folds to lowercase. - Check whether the cursor is still open in that session. In psql, run
SELECT * FROM pg_cursors;. This view lists all currently open cursors in the current session, including their names and whether they are holdable. If the name appears, the cursor is still open and must be closed before reuse. Note thatpg_cursorsonly shows cursors for the session you are connected to; other sessions' cursors are not visible. - Close the existing cursor if you no longer need it. Run
CLOSE cursor_name;using the exact name. If you are inside a transaction, you can also let the transaction end: a non-holdable cursor is closed automatically atCOMMITorROLLBACK. After closing, declare the cursor again with the same name. - Use a unique name per cursor. If your code declares multiple cursors in one session, generate distinct names, for example by appending a counter, a timestamp, or a UUID fragment. Avoid reusing a fixed name in a loop unless you close it each iteration.
- Check your transaction boundaries. A cursor declared with
WITH HOLDsurvivesCOMMITand remains open until you explicitlyCLOSEit or the session ends. If you useWITH HOLD, make sure you close it before declaring another cursor with the same name. Conversely, if you rely on implicit closing at transaction end, confirm your code actually commits or rolls back before the next declaration. - Inspect application or ORM code for repeated declarations. Connection pools reuse sessions, so a cursor left open by one request can collide with a later request on the same pooled connection. Search your codebase for
DECLAREstatements and ensure each path closes its cursor, or that names are generated per call. In PL/pgSQL, useOPENandCLOSEon ref cursors carefully; a bound cursor variable that is reopened without closing can trigger the same class of error. - Test the corrected flow. Run the full sequence: declare, fetch, close, then declare again with the same name. Confirm no error appears. Then run two declarations with different names in the same transaction to confirm unique naming works. Finally, test the pooled-connection scenario if applicable by running the operation twice in succession on the same connection.
Common Mistakes
- Assuming the cursor is global. Cursor names are scoped to the session. Another connection using the same name is not the cause; the conflict is within your own session.
- Forgetting that
WITH HOLDcursors outlive transactions. These cursors remain open afterCOMMITand must be closed explicitly. Code that expects automatic cleanup at transaction end will hit 42P03 on the next declaration. - Reusing a name inside a loop without closing. Declaring the same cursor name repeatedly in a procedure or script without a matching
CLOSEaccumulates open cursors and triggers the error on the second iteration. - Mixing quoted and unquoted identifiers.
DECLARE MyCursor CURSOR ...creates a cursor namedmycursor, whileDECLARE "MyCursor" CURSOR ...creates one namedMyCursor. These are different names, which can cause confusion when closing or checking for duplicates. - Ignoring connection pooling. In pooled environments, a cursor left open by a previous request can cause the error in an unrelated later request that reuses the same physical connection.
Tips
- Prefer closing cursors explicitly even when the transaction would close them automatically; it makes the lifecycle obvious and avoids surprises with
WITH HOLD. - Use
pg_cursorsduring debugging to confirm which cursors are open in the current session before and after your statements. - If you generate cursor names dynamically, keep them short and avoid special characters that require quoting.
- In application code, wrap cursor use in a
try/finallyblock (or your language's equivalent) so theCLOSEruns even when an error occurs mid-fetch. - When using PL/pgSQL, remember that ref cursors bound to variables follow the same naming rules; close them before reopening.
Troubleshooting
If CLOSE cursor_name; returns an error saying the cursor does not exist, check the exact spelling and case. Unquoted names are folded to lowercase, so CLOSE MyCursor; looks for mycursor. If the cursor is not in pg_cursors but the error persists, confirm you are connected to the same session that produced the error; a different psql window or connection will not show it. If the error appears only under load, suspect connection pooling and audit code paths that declare cursors without closing them. If you cannot find the declaration in your own code, check triggers, stored procedures, or ORM-generated SQL that may declare cursors internally. In rare cases, a long-running transaction that never commits keeps non-holdable cursors open longer than expected; review transaction handling. If closing and renaming do not resolve it, restart the session (disconnect and reconnect) to clear all cursors, then retest to confirm the cause was an open cursor rather than a naming conflict elsewhere.
Frequently Asked Questions
Is error 42P03 caused by another user's cursor?
No. Cursor names are scoped to a single session. The conflict is always with a cursor open in your own connection.
Do cursors close automatically at the end of a transaction?
Yes, unless declared WITH HOLD. Holdable cursors survive COMMIT and must be closed explicitly with CLOSE or by ending the session.
How can I see which cursors are open?
Query SELECT * FROM pg_cursors; in the session of interest. It lists open cursors for that session only.
Can two sessions use the same cursor name?
Yes. Because cursor names are session-scoped, two connections can each declare a cursor with the same name without conflict.
Does closing a cursor free its result set?
Closing a cursor releases the portal and its resources. Any rows not yet fetched are discarded and cannot be retrieved afterward.
Why does the error appear only sometimes?
It depends on whether a cursor with that name is still open when the declaration runs. Transaction timing, WITH HOLD usage, and connection pooling all affect when that happens.