SQLSTATE 42P03 ERROR Class 42: Syntax Error or Access Rule Violation

duplicate_cursor cursor “…” already exists — 42P03

PostgreSQL error "cursor "…" already exists" (SQLSTATE 42P03): what it means, common causes, and how to fix it.

PG 12, 13, 14, 15, 16, 17, 18 Official docs
Last reviewed May 2025 Grounded in source

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

  1. Close the existing cursor first: CLOSE mycursor; then re-declare.
  2. Use unique cursor names, or CLOSE ALL; between iterations.
  3. Wrap cursor use so each is closed when finished.

Related & next steps

Reference: PostgreSQL 18 — DECLARE.

Was this helpful?