42P11
PostgreSQLERRORNotableSyntax Error or Access Rule ViolationHIGH confidence

invalid cursor definition

What this means

SQLSTATE 42P11 is raised when a cursor definition is structurally invalid — for example, using FOR UPDATE on a cursor query that contains a JOIN, DISTINCT, or aggregate which makes the cursor non-updatable.

Why it happens
  1. 1DECLARE ... FOR UPDATE on a cursor query that is not simple enough to support row-level locking (contains JOINs, DISTINCT, GROUP BY, etc.)
How to reproduce

FOR UPDATE cursor with a JOIN.

trigger — this will error
trigger — this will error
DECLARE my_cursor CURSOR FOR
  SELECT e.*, d.name FROM employees e JOIN departments d ON e.dept_id = d.id
  FOR UPDATE;

expected output

ERROR:  cursor FOR UPDATE/SHARE is not allowed with joins

Fix 1

Remove FOR UPDATE from cursors with JOINs

WHEN When row locking is not needed.

Remove FOR UPDATE from cursors with JOINs
DECLARE my_cursor CURSOR FOR
  SELECT e.*, d.name FROM employees e JOIN departments d ON e.dept_id = d.id;

Why this works

FOR UPDATE is only supported on simple single-table cursor queries.

Fix 2

Separate the cursor query to a single table for locking

WHEN When row locking is required.

Separate the cursor query to a single table for locking
DECLARE my_cursor CURSOR FOR
  SELECT * FROM employees FOR UPDATE;

Why this works

Use a simple single-table cursor with FOR UPDATE, then join other tables in the processing loop if needed.

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