PG
PRO
42P04ERRORTier 2 — Caution✅ HIGH confidence

duplicate database

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

What this means

SQLSTATE 42P04 is raised when CREATE DATABASE is attempted with a name that already exists in the cluster.

Why it happens

  1. 1CREATE DATABASE specifying a name that is already in use by an existing database

How to reproduce

Creating a database that already exists.

trigger — this will ERROR
CREATE DATABASE myapp; -- myapp database already exists
ERROR: database "myapp" already exists

Fix 1: Use CREATE DATABASE IF NOT EXISTS (not available in Postgres) — check first

In provisioning scripts that may run multiple times.

fix
SELECT 1 FROM pg_database WHERE datname = 'myapp';
-- Only CREATE if the query returns no rows

Why this works

Check pg_database before creating. Unlike PostgreSQL 15+ schemas (which have IF NOT EXISTS), databases require a manual existence check.

Fix 2: Drop and recreate the database if a fresh database is needed

In test environments where the database should be reset.

fix
DROP DATABASE IF EXISTS myapp;
CREATE DATABASE myapp;

Why this works

DROP DATABASE IF EXISTS safely removes the existing database before creating a fresh one.

What not to do

DROP DATABASE in production without a backup

Why it's wrong: DROP DATABASE is irreversible without a backup.

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

CREATE DATABASEpg_database
⚙️ 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 →