42P04ERRORTier 2 — Caution✅ HIGH confidenceduplicate database
What this means
SQLSTATE 42P04 is raised when CREATE DATABASE is attempted with a name that already exists in the cluster.
Why it happens
- 1CREATE DATABASE specifying a name that is already in use by an existing database
How to reproduce
Creating a database that already exists.
CREATE DATABASE myapp; -- myapp database already existsFix 1: Use CREATE DATABASE IF NOT EXISTS (not available in Postgres) — check first
In provisioning scripts that may run multiple times.
SELECT 1 FROM pg_database WHERE datname = 'myapp';
-- Only CREATE if the query returns no rowsWhy 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.
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
🔗 Related errors
📄 Reference pages