Diagnostic Queries
Symptoms
A DECLARE tried to create a cursor whose name is already in use in the session. PostgreSQL raises SQLSTATE 42P03 (duplicate_cursor).
- A cursor with that name already exists.
- Common when re-declaring without closing the previous one.
- Cursor names must be unique within a session.
What the server log shows
ERROR: cursor "mycursor" already exists
Why PostgreSQL raises this — what the manual says
the DECLARE reference (Parameters):
“This must be different from any other active cursor name in the session.”
Cursor names are unique per session. Declaring a second cursor with a name still in use collides with the existing one, so PostgreSQL reports 42P03.
Common causes
- Re-declaring a cursor without closing the previous one.
- Reusing a fixed cursor name in a loop.
- A non-holdable cursor from a prior statement still open.
How to fix it
- Close the existing cursor first:
CLOSE mycursor;then re-declare. - Use unique cursor names, or
CLOSE ALL;between iterations. - Wrap cursor use so each is closed when finished.
Related & next steps
Reference: PostgreSQL 18 — DECLARE.
Thanks — noted. This helps keep the database accurate.