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
- Deallocate first:
DEALLOCATE stmt1;then re-prepare. - Run
DISCARD ALL;when checking a connection back into a pool. - Let the driver manage prepared-statement names, or use unnamed statements.
Related & next steps
Reference: PostgreSQL 18 — PREPARE.
Thanks — noted. This helps keep the database accurate.