42P04
PostgreSQLERRORNotableSyntax Error or Access Rule ViolationHIGH confidence

duplicate 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
  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
trigger — this will error
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.

Use CREATE DATABASE IF NOT EXISTS (not available in Postgres) — check first
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 and recreate the database if a fresh database is needed
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

DROP DATABASE is irreversible without a backup.

Sources
Official documentation ↗

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

← All PostgreSQL errors