PostgreSQL Error 42P07: Duplicate Table

PostgreSQL error 42P07 (Duplicate Table) explained: what it means, why it happens, and how to fix it — with copy-paste code examples.

SQLSTATE 42P07 PostgreSQL Last verified 2026-08-26

Quick Answer

Use CREATE TABLE IF NOT EXISTS for idempotent scripts. If that does not apply, check existence first with SELECT to_regclass('public.users') — the full checklist is below.

Error Code

SQLSTATE: 42P07
Official name: Duplicate Table
System name: duplicate_table
Service: PostgreSQL

What does this error mean?

The statement attempted to create a table, view, or index whose name already exists in the target schema.

Exact Error Messages

You may see this error reported as one of the following messages:

Common Causes

How to Fix

  1. Use CREATE TABLE IF NOT EXISTS for idempotent scripts
  2. Check existence first with SELECT to_regclass('public.users')
  3. If the old table is truly unwanted, drop it explicitly before recreating
  4. Let a versioned migration tool own the schema instead of ad-hoc scripts

Code Examples

Idempotent create sql
CREATE TABLE IF NOT EXISTS users (
  id bigserial PRIMARY KEY,
  email text UNIQUE NOT NULL
);

IF NOT EXISTS turns a would-be 42P07 into a no-op when the relation already exists.

Check before creating sql
SELECT to_regclass('public.users') IS NULL AS missing;

to_regclass returns NULL when the relation does not exist, letting scripts branch safely.

Framework-Specific Fixes

sqlalchemy

Pass checkfirst=True to create_all() so existing tables are skipped instead of raising 42P07.

Base.metadata.create_all(engine, checkfirst=True)

django

If the table exists but Django's migration history does not, mark the migration applied with --fake instead of re-creating the table.

python manage.py migrate myapp 0001 --fake

prisma

Use prisma migrate deploy in CI/CD; it only applies unapplied migrations and never re-creates existing tables.

npx prisma migrate deploy

You Might Also Like

Frequently Asked Questions

Why am I seeing PostgreSQL error 42P07?

Most often this happens when running a setup script twice without IF NOT EXISTS, or when re-running migrations against a database that already contains the tables.

How do I fix PostgreSQL error 42P07?

Use CREATE TABLE IF NOT EXISTS for idempotent scripts.

Which frameworks have documented fixes for error 42P07?

This page documents fixes for: sqlalchemy, django, prisma.

Official Sources

This page is based on the official PostgreSQL documentation linked below and adds practical troubleshooting guidance on top.