42P05
PostgreSQLERRORNotableSyntax Error or Access Rule ViolationHIGH confidence

duplicate prepared statement

What this means

SQLSTATE 42P05 is raised when PREPARE is called with a statement name that already exists in the current session. Prepared statement names must be unique within a session.

Why it happens
  1. 1PREPARE uses a name that was already used by a previous PREPARE call in the same session and not yet deallocated
How to reproduce

PREPARE with a name that is already prepared.

trigger — this will error
trigger — this will error
PREPARE my_query AS SELECT * FROM orders WHERE id = $1;
PREPARE my_query AS SELECT * FROM customers WHERE id = $1; -- duplicate

expected output

ERROR:  prepared statement "my_query" already exists

Fix 1

DEALLOCATE the existing prepared statement before re-preparing

WHEN When reusing a prepared statement name.

DEALLOCATE the existing prepared statement before re-preparing
DEALLOCATE my_query;
PREPARE my_query AS SELECT * FROM customers WHERE id = $1;

Why this works

DEALLOCATE removes the named prepared statement, freeing the name for reuse.

Fix 2

Use unique names or DEALLOCATE ALL before re-preparing

WHEN In application code that prepares statements on each connection.

Use unique names or DEALLOCATE ALL before re-preparing
DEALLOCATE ALL; -- clear all prepared statements in the session

Why this works

DEALLOCATE ALL removes all prepared statements in the session, useful for connection reset in connection pools.

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