42P03
PostgreSQLERRORNotableSyntax Error or Access Rule ViolationHIGH confidence

duplicate cursor

What this means

SQLSTATE 42P03 is a Postgres-specific error raised when a DECLARE CURSOR statement attempts to create a cursor with a name that is already in use in the current transaction.

Why it happens
  1. 1DECLARE CURSOR uses a name that was already declared and not yet closed in the current session or transaction
How to reproduce

Declaring a cursor with a duplicate name.

trigger — this will error
trigger — this will error
DECLARE my_cursor CURSOR FOR SELECT * FROM orders;
DECLARE my_cursor CURSOR FOR SELECT * FROM customers; -- duplicate name

expected output

ERROR:  cursor "my_cursor" already exists

Fix 1

Close the existing cursor before declaring a new one with the same name

WHEN When cursor names may clash.

Close the existing cursor before declaring a new one with the same name
CLOSE my_cursor;
DECLARE my_cursor CURSOR FOR SELECT * FROM customers;

Why this works

CLOSE releases the cursor name, allowing it to be reused.

Fix 2

Use unique cursor names

WHEN When managing multiple cursors in a stored procedure.

Why this works

Generate unique cursor names (e.g., including a counter or timestamp suffix) to avoid name collisions.

Sources
Official documentation ↗

Class 42 — Syntax Error or Access Rule Violation (Postgres-specific)

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All PostgreSQL errors