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

duplicate_prepared_statement prepared statement “…” already exists — 42P05

PostgreSQL error "prepared statement "…" already exists" (SQLSTATE 42P05): 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 PREPARE used a name that already exists in the current session. Prepared statement names must be unique per session, so PostgreSQL raises SQLSTATE 42P05 (duplicate_prepared_statement).

  • The session already has a prepared statement with that name.
  • Common with poolers reusing a connection that still holds the name.
  • You must deallocate before re-preparing the same name.

What the server log shows

ERROR:  prepared statement "stmt1" already exists

Why PostgreSQL raises this — what the manual says

the PREPARE reference (Parameters):

“It must be unique within a single session and is subsequently used to execute or deallocate a previously prepared statement.”

Each session keeps a namespace of prepared statements. Preparing a name that is already in use would overwrite an existing plan ambiguously, so PostgreSQL rejects it with 42P05.

Common causes

  • A pooled connection still holds a statement of that name from a prior client.
  • Re-preparing the same name without deallocating first.
  • A driver that auto-names prepared statements and collides after reconnect.

How to fix it

  1. Deallocate first: DEALLOCATE stmt1; then re-prepare.
  2. Run DISCARD ALL; when checking a connection back into a pool.
  3. Let the driver manage prepared-statement names, or use unnamed statements.

Related & next steps

Reference: PostgreSQL 18 — PREPARE.

Was this helpful?