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.

Introduction & Quick Summary
A migration stops on a CREATE that has already been applied:
ERROR: relation "users" already exists
SQL state: 42P07psql:/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_pathresolves 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; schema | relname | relkind
--------+---------+---------
public | users | rrelkind 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:
| SQLSTATE | Message | Cause |
|---|---|---|
| 42P07 | relation already exists | table, index, view, or sequence name taken |
| 42710 | duplicate object: constraint already exists | constraint name taken on that table |
| 42P06 | schema already exists | CREATE SCHEMA without IF NOT EXISTS |
| 42P16 | invalid table definition | conflicting column options in one statement |
| 23505 | duplicate key value violates unique constraint | data, not DDL |
| 3F000 | schema does not exist | wrong search_path or a typo |
Key Comparison Table
| Approach | Statement | Hides drift | Use in migrations |
|---|---|---|---|
| Guarded create | CREATE TABLE IF NOT EXISTS | yes, column changes are ignored | bootstrap scripts only |
| Migration tracking | version table plus one apply per version | no | the default for application schema |
| Advisory lock | pg_advisory_lock(key) around the migration | no | concurrent deploys |
| Separate schema per environment | search_path set in the connection | no | multi-tenant designs |
| Deterministic names | CREATE INDEX idx_users_email | no | avoids accidental collisions |
| Manual repair | inspect pg_class, then correct | no | recovering a failed run |
Where IF NOT EXISTS is available:
| Object | Supports IF NOT EXISTS | Note |
|---|---|---|
| Table | yes, since 9.1 | does not compare columns |
| Index | yes, since 9.5 | does not compare columns or predicate |
| View | no | wrap in DO block or use CREATE OR REPLACE VIEW |
| Sequence | yes, since 9.5 | does not compare increment |
| Materialized view | no | check pg_matviews first |
| Column | ADD COLUMN IF NOT EXISTS since 9.6 | does 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;-- 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 documentationThe SQL documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit SQL work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related SQL guides
All SQL guidesSQLite: database is locked (SQLITE_BUSY) under concurrent writes
SQLite allows one writer. Set a busy timeout, switch to WAL, start write transactions as IMMEDIATE, and reduce to a single writer connection.
SQL Window Functions: ROW_NUMBER, RANK, DENSE_RANK, and LEAD/LAG Explained
How the four ranking and offset functions differ on ties, why the default RANGE frame makes running totals repeat, and how LAG builds gap-and-island.
Postgres: column does not exist (SQLSTATE 42703)
42703 means the identifier you wrote is not the one that exists. Check case folding, alias scope, search_path and migration drift.
PostgreSQL: canceling statement due to statement timeout
The statement was canceled by statement_timeout. Find whether the role, the pooler or the client set it, then scope a longer budget to that job.
More in SQL
All SQL guidesThe guides filed next to this one in SQL, in library order.