Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Postgres: relation already exists (42P07) during migrations

42P07 means the object is already there, often because a failed migration left half its DDL applied. Make DDL idempotent and verify what actually exists.

~5 min readSQL
#postgresql#sql#migrations#ddl
Bold white headline reading ALREADY EXISTS with a Postgres schema crate blocked at an amber duplicate table gate.

Introduction & Quick Summary

A migration stops on a CREATE that has already been applied:

code
ERROR: relation "users" already exists SQL state: 42P07
psql:/migrations/0003_users.sql:6: error: relation "users" already exists

42P07 is raised when a CREATE statement targets a name that a relation already uses in the target schema. A relation is broader than a table: indexes, views, materialized views, and sequences all occupy the same namespace, so an index named users blocks a table named users in the same schema.

Where it appears:

  • A migration ran to completion but the migration tool did not record it, so the next run repeats it.
  • A statement failed halfway through a file and the rest was re-run from the top.
  • Two deployments started at once and both ran the same migration.
  • search_path resolves the name in a different schema than intended.
  • An index was created with a name that collides with a table or another index.
  • A test suite recreates the schema while a previous run's connection still holds objects.

Quick answer: find out what already exists and why, make the DDL idempotent where that is honest, and never edit a migration that has already been applied.

Core Mechanics, Signatures & Reproducible Setup

Postgres resolves a CREATE name against the pg_class namespace of the target schema. If a row with that name exists, it raises 42P07 before any DDL runs. Transactional DDL means a failure inside BEGIN rolls everything back, but many migration runners send each statement separately and commit files in pieces, which leaves partial state.

-- repro CREATE TABLE users (id bigserial PRIMARY KEY, email text NOT NULL); CREATE TABLE users (id bigserial PRIMARY KEY, email text NOT NULL); -- ERROR: relation "users" already exists -- the same error from a different object type CREATE INDEX users ON users (email); -- ERROR: relation "users" already exists
-- what occupies the name SELECT n.nspname AS schema, c.relname, c.relkind FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE c.relname = 'users' ORDER BY 1, 2;
text
schema | relname | relkind --------+---------+--------- public | users | r

relkind tells you what it is: r table, i index, v view, m materialized view, S sequence, p partitioned table.

Nearby errors and their distinct causes:

SQLSTATEMessageCause
42P07relation already existstable, index, view, or sequence name taken
42710duplicate object: constraint already existsconstraint name taken on that table
42P06schema already existsCREATE SCHEMA without IF NOT EXISTS
42P16invalid table definitionconflicting column options in one statement
23505duplicate key value violates unique constraintdata, not DDL
3F000schema does not existwrong search_path or a typo

Key Comparison Table

ApproachStatementHides driftUse in migrations
Guarded createCREATE TABLE IF NOT EXISTSyes, column changes are ignoredbootstrap scripts only
Migration trackingversion table plus one apply per versionnothe default for application schema
Advisory lockpg_advisory_lock(key) around the migrationnoconcurrent deploys
Separate schema per environmentsearch_path set in the connectionnomulti-tenant designs
Deterministic namesCREATE INDEX idx_users_emailnoavoids accidental collisions
Manual repairinspect pg_class, then correctnorecovering a failed run

Where IF NOT EXISTS is available:

ObjectSupports IF NOT EXISTSNote
Tableyes, since 9.1does not compare columns
Indexyes, since 9.5does not compare columns or predicate
Viewnowrap in DO block or use CREATE OR REPLACE VIEW
Sequenceyes, since 9.5does not compare increment
Materialized viewnocheck pg_matviews first
ColumnADD COLUMN IF NOT EXISTS since 9.6does not compare type

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Find what exists before changing the migration

The error names the object, and the catalogue says what kind of object it is. Read that first; the fix differs between a table that should exist and an index that accidentally took the name.

SELECT c.relname, c.relkind, pg_size_pretty(pg_total_relation_size(c.oid)) AS size, pg_get_userbyid(c.relowner) AS owner FROM pg_class c WHERE c.relname IN ('users', 'users_email_idx');
-- does the existing table match what the migration wanted? SELECT column_name, data_type, is_nullable, column_default FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'users' ORDER BY ordinal_position;

If the shape matches, the migration is a duplicate and should be marked as applied. If the shape differs, the migration is not a duplicate and needs a corrective statement, not IF NOT EXISTS.

2. Use guarded DDL only where drift is impossible

CREATE TABLE IF NOT EXISTS skips the whole statement when the table exists, including any column that the migration intended to add. That makes it safe for bootstrap and dangerous for schema evolution.

-- bootstrap: safe, the table is either complete or created here CREATE TABLE IF NOT EXISTS job_locks ( id bigserial PRIMARY KEY, name text NOT NULL UNIQUE, locked_at timestamptz NOT NULL DEFAULT now() );
-- evolution: each change is guarded separately ALTER TABLE users ADD COLUMN IF NOT EXISTS locale varchar(8); CREATE INDEX IF NOT EXISTS idx_users_locale ON users (locale); COMMENT ON COLUMN users.locale IS 'BCP 47 language tag';

Column guards work per statement, so a new column added later is applied even when the table already existed. COMMENT ON is naturally idempotent.

3. Fix a schema resolution problem

The same name can exist in two schemas, and search_path decides which one CREATE checks.

SHOW search_path; -- "$user", public -- create into an explicit schema, never rely on the session default CREATE TABLE IF NOT EXISTS app.users (id bigserial PRIMARY KEY);
-- where does the existing relation live? SELECT n.nspname, c.relkind FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE c.relname = 'users';

If production has app.users and the migration creates users, both exist and queries hit whichever search_path names first. Set the schema in the migration and in the application's connection string so they cannot diverge.

4. Serialize concurrent migrations

Two pods starting at once both check the version table, both see an unapplied migration, and one of them gets 42P07. An advisory lock makes the second wait.

BEGIN; SELECT pg_advisory_xact_lock(4815162342); -- run the migration statements here COMMIT;
sql
-- a locking wrapper for a whole file DO $$ BEGIN PERFORM pg_advisory_xact_lock(hashtext('schema-migrations')); END $$;

pg_advisory_xact_lock releases automatically at commit or rollback, so a crashed migration does not leave the lock held. The key is arbitrary but must be identical in every process that migrates.

5. Recover a half-applied migration

Never edit the applied file. Read the current state, then write a new migration that brings the schema to where the old one intended.

-- what exists now SELECT relname, relkind FROM pg_class WHERE relnamespace = 'public'::regnamespace AND relkind IN ('r','i','v','S'); -- what the version table believes SELECT * FROM schema_migrations ORDER BY version DESC LIMIT 5;
-- 0004_repair_users.sql: make the intended state true, idempotently CREATE TABLE IF NOT EXISTS users ( id bigserial PRIMARY KEY, email text NOT NULL ); ALTER TABLE users ADD COLUMN IF NOT EXISTS created_at timestamptz NOT NULL DEFAULT now(); CREATE UNIQUE INDEX IF NOT EXISTS idx_users_email ON users (email);

Then insert the missing version row only after the SQL succeeds, so the next deploy does not replay the broken file. Review the resulting schema against the pg_dump --schema-only output with the SQL schema tool and Diff to confirm the repair matches the intended design.

Common Compilation/Runtime Mistakes & Version Gotchas

Marking a failed migration as applied. The version table then lies, and the next migration builds on a schema that is missing part of its base. Repair first, then record.

Editing an applied migration. Some environments have already run the old text, some have not, and the file no longer matches either. Add a new migration instead; that rule has no exceptions worth making.

Assuming DDL is all-or-nothing. A file sent statement by statement commits each successful statement. Wrap the file in an explicit transaction when the tool allows it, so the failure leaves the schema unchanged.

Creating objects with generic names. CREATE INDEX ON users (email) generates users_email_idx, which collides with a table of that name created later. Name indexes explicitly and check pg_class for the name first.

Docker Compose and test databases that reuse volumes. A named volume keeps the schema between runs, and a bootstrap script with CREATE TABLE fails on the second start. Drop the volume for a clean run, or use the guards from section 2.

Version differences worth knowing. CREATE TABLE IF NOT EXISTS arrived in 9.1, CREATE INDEX IF NOT EXISTS and CREATE SEQUENCE IF NOT EXISTS in 9.5, and ADD COLUMN IF NOT EXISTS in 9.6. Migrations that must run on older servers cannot use these guards. PostgreSQL 11 and later support transactional CREATE INDEX CONCURRENTLY restrictions differently; it still cannot run inside a transaction block, so a migration tool that wraps files in one will fail with a different error.

Verification. After the repair, run the migration from an empty database and from a copy of production. The first proves the file is complete, the second proves it is safe on existing data. Running only one of them is how 42P07 comes back next quarter.

Reference material: CREATE TABLE and ALTER TABLE.

Official references

primary documentation

The SQL documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit SQL work — they run entirely in this browser tab, so nothing you paste leaves your device.

All SQL guides

More in SQL

All SQL guides

The guides filed next to this one in SQL, in library order.