PG
PRO
42P05ERRORTier 2 — Caution✅ HIGH confidence

duplicate prepared statement

Category: Syntax Error or Access Rule ViolationVersions: All Postgres versions

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
PREPARE my_query AS SELECT * FROM orders WHERE id = $1;
PREPARE my_query AS SELECT * FROM customers WHERE id = $1; -- duplicate
ERROR: prepared statement "my_query" already exists

Fix 1: DEALLOCATE the existing prepared statement before re-preparing

When reusing a prepared statement name.

fix
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

In application code that prepares statements on each connection.

fix
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 docs: https://www.postgresql.org/docs/current/errcodes-appendix.html

🔧 Source ref: Class 42 — Syntax Error or Access Rule Violation (Postgres-specific)

Confidence assessment

✅ HIGH confidence

Postgres-specific. Stable across all versions.

See also

📄 Reference pages

PREPAREDEALLOCATEpg_prepared_statements
⚙️ This error reference was generated with AI assistance and reviewed for accuracy. Examples are provided to illustrate common scenarios and may not cover every case. Always test fixes in a development environment before applying to production. Spotted an error? Suggest a correction →