Error 42P04 duplicate_database appears when you try to create a database that already exists in PostgreSQL.
PostgreSQL error 42P04 – duplicate_database – means the CREATE DATABASE statement collided with an existing database name. Connect to a different database, rename or drop the conflicting database, or choose a unique name to resolve the issue.
PostgreSQL Error 42P04
Error 42P04, condition name duplicate_database, is raised when a CREATE DATABASE command uses a name that is already present in pg_database.
The server aborts the statement to prevent accidental overwriting, so the new database is not created. Fixing it is critical because subsequent scripts may rely on the database being available.
The most common trigger is running CREATE DATABASE in a deployment script without checking for existence.
Automated CI pipelines that run multiple times often surface the issue.
Manual commands in psql or GUI tools also raise 42P04 if the chosen name matches an existing database, including those marked as templates.
First, verify whether the database truly exists by querying pg_database or listing databases in psql.
Then pick one of the fixes below.
Drop, rename, or reuse the existing database, or adjust the script to create the database only when it is absent.
CI/CD reruns - incorporate an existence check to skip creation during repeated deployments.
Local development refresh - developers can DROP DATABASE safely when no other sessions are connected, then recreate.
Use idempotent scripts: wrap CREATE DATABASE inside a DO block that checks pg_database.
Name databases uniquely across environments by appending environment suffixes like _dev or _test.
Error 23505 duplicate_key arises on unique constraint violations and is fixed by removing or changing conflicting rows.
Error 42P07 duplicate_table fires when CREATE TABLE meets an existing table and is handled similarly by renaming, dropping, or checking first.
.
No. You must emulate the check using DO blocks, PL/pgSQL functions, or conditional scripts.
Wrap the statement in BEGIN ... EXCEPTION WHEN duplicate_database THEN RAISE NOTICE to swallow the error if desired.
Active connections prevent DROP DATABASE. Terminate them with pg_terminate_backend or disconnect clients first.
Galaxy’s AI copilot flags existing databases during autocomplete and encourages idempotent snippets, reducing collision risk.