duplicate database
SQLSTATE 42P04 is raised when CREATE DATABASE is attempted with a name that already exists in the cluster.
- 1CREATE DATABASE specifying a name that is already in use by an existing database
Creating a database that already exists.
CREATE DATABASE myapp; -- myapp database already exists
expected output
ERROR: database "myapp" already exists
Fix 1
Use CREATE DATABASE IF NOT EXISTS (not available in Postgres) — check first
WHEN In provisioning scripts that may run multiple times.
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
WHEN 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.
✕ DROP DATABASE in production without a backup
DROP DATABASE is irreversible without a backup.
Class 42 — Syntax Error or Access Rule Violation (Postgres-specific)
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev