Raised when a PREPARE command uses a statement name that already exists in the current session.
duplicate_prepared_statement occurs when you issue PREPARE with a name already in use within your PostgreSQL session. Deallocate or rename the existing statement to resolve the error.
duplicate_prepared_statement
PostgreSQL raises duplicate_prepared_statement (SQLSTATE 42P05) when a PREPARE command reuses a statement name already defined in the current backend session. The server blocks the second definition to protect the existing execution plan.
The error surfaces in psql, application pools, or ORMs that dynamically create prepared statements.
Until the conflict is cleared, subsequent requests can fail, stall transactions, and exhaust connection-pool slots, so fixing it quickly is critical.
A client issues PREPARE twice with the same identifier without running DEALLOCATE or closing the connection.
The second PREPARE triggers the conflict immediately.
Connection pools that reuse sessions across requests can retain prepared statements between API calls, surprising stateless application code that expects a clean slate.
First, remove the old statement with DEALLOCATE or DEALLOCATE ALL, then issue PREPARE again.
Alternatively, choose a unique name, or omit the name to let PostgreSQL create an unnamed statement.
If the statement is created by an ORM, enable its prepared-statement cache eviction or set a unique hash in the name template to avoid collisions.
psql scripts rerun interactively - add DEALLOCATE ALL at the top or use \set AUTOCOMMIT off to force a new session.
Java apps using PgJDBC with prepareThreshold>0 - set autosave=always so the driver automatically DEALLOCATEs on failure.
Always DEALLOCATE named statements in cleanup blocks or finally clauses.
In pooled environments, prefer unnamed statements or hashed names.
Monitor pg_prepared_statements and set statement_timeout on DEALLOCATE to keep the catalog clean. Galaxy’s editor warns when a duplicate name is detected and can auto-insert DEALLOCATE before reruns.
SQLSTATE 42P03 undefined_cursor appears when FETCH targets a non-existent cursor. SQLSTATE 42P02 undefined_parameter occurs when PREPARE references an invalid placeholder. Both clear when the session state is reset.
.
Running DEALLOCATE ALL is lightweight. It only removes catalog entries for prepared statements inside the current session and does not lock tables.
Yes. Many drivers allow disabling prepares by sending simple queries. In pgJDBC set prepareThreshold=0, but you lose server-side planning benefits.
If a new application version prepares the same name but different SQL, the old statement remains in pooled sessions, triggering the error until the pool restarts or DEALLOCATE runs.
Galaxy’s SQL editor tracks prepared statements per connection tab and automatically issues DEALLOCATE when you rerun a script, preventing name collisions.