SQLSTATE 42P04 ERROR Class 42: Syntax Error or Access Rule Violation

duplicate_database database “…” already exists — 42P04

PostgreSQL error "database "…" already exists" (SQLSTATE 42P04): what it means, common causes, and how to fix it.

PG 12, 13, 14, 15, 16, 17, 18 Official docs
Last reviewed May 2025 Grounded in source

Diagnostic Queries

Symptoms

A CREATE DATABASE tried to create a database whose name already exists. PostgreSQL raises SQLSTATE 42P04 (duplicate_database).

  • A database with that name already exists in the cluster.
  • Database names are unique cluster-wide.
  • Common in re-run provisioning scripts.

What the server log shows

ERROR:  database "appdb" already exists

Why PostgreSQL raises this — what the manual says

As the CREATE DATABASE reference (Description) explains:

A database with the requested name already exists; database names must be unique across the entire cluster, so choose a different name or drop the existing database first (CREATE DATABASE does not support IF NOT EXISTS).

Database names are unique within a cluster. Creating one that already exists collides with the existing database, so PostgreSQL reports 42P04.

Common causes

  • Re-running a provisioning script.
  • The database was created earlier.
  • A name clash with an existing database.

How to fix it

  1. Check existence first: query pg_database or use \l.
  2. Drop and recreate only if intended (irreversible — back up first).
  3. Choose a unique database name.

Related & next steps

Reference: PostgreSQL 18 — CREATE DATABASE.

Was this helpful?