Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

PostgreSQL Error 42P07: Duplicate Table Fix

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

PostgreSQL error 42P07 means the object you tried to create already exists in the target schema — the SQLSTATE code for duplicate_table. The fastest fix is to make the statement tolerant of an existing object: use CREATE TABLE IF NOT EXISTS, or drop the old table first if it is genuinely obsolete, or create the new table under a different name or schema. Before you change anything, run \dt (or query information_schema.tables) to see exactly what PostgreSQL thinks is already there, because the culprit is sometimes a table you forgot about, a leftover from a failed migration, or an object in a different schema than the one you assumed.

What You'll Need

  • Access to a PostgreSQL client — psql, pgAdmin, DBeaver, or whatever tool your team uses.
  • Credentials for a role that owns (or can create objects in) the target schema. Error 42P07 is a naming conflict, not a permissions problem, but you need enough rights to inspect and alter the object.
  • The exact SQL statement that failed, including the schema name if one was specified.
  • A backup or a transaction you can roll back if you decide to drop data. Dropping a table destroys its rows permanently.

Step-by-Step

  1. Read the full error message. PostgreSQL prints something like ERROR: relation "orders" already exists with the SQLSTATE 42P07. The relation name in the message is the object it collided with. Note the exact spelling, including case — unquoted identifiers are folded to lowercase, so Orders and orders are the same table unless you quoted the name.
  2. Connect to the right database. A very common cause is being connected to a different database than you think. Run \c in psql or check the connection string. Tables are scoped per database, so the same name can exist in one database and not another.
  3. List the tables in the schema. In psql, \dt shows tables in the current search path; \dt schema_name.* shows a specific schema. From SQL, run SELECT table_schema, table_name FROM information_schema.tables WHERE table_name = 'your_table'; to see every schema that contains a table with that name.
  4. Check the search path. Run SHOW search_path;. If it includes multiple schemas, CREATE TABLE foo creates in the first writable schema, but an existing foo in a later schema can still cause confusion when you query. Qualify names explicitly (myschema.foo) to remove ambiguity.
  5. Decide what the existing object is. Inspect it with \d your_table or \d+ your_table to see columns, indexes and ownership. If it holds real data, do not drop it casually — the duplicate may be the one you actually want to keep.
  6. Pick a resolution. Three legitimate options:
    • Make the statement idempotent: change CREATE TABLE to CREATE TABLE IF NOT EXISTS. PostgreSQL then issues a notice instead of an error and leaves the existing table untouched. Note that it does not verify the existing table's structure matches what you intended.
    • Drop and recreate: DROP TABLE your_table; then re-run the create. Only do this if you are certain the data is disposable — take a backup first, or wrap both statements in a transaction and roll back if anything looks wrong.
    • Use a new name or schema: create your_table_v2 or newschema.your_table. This is the safest option in production when the existing table is live.
  7. Re-run the corrected statement and confirm success. Then verify with \d your_table that the object has the columns and constraints you expect.
  8. Fix the source, not just the symptom. If the error came from an application migration or an ORM, edit the migration file so it does not blindly re-create tables. Migration tools such as Flyway, Liquibase or Alembic usually track applied versions; a duplicate-table error often means a migration was run twice, or run against a database that already had the schema applied by hand.

Common Mistakes

  • Assuming it is a permissions error. 42P07 is about existence, not rights. Granting more privileges will not fix it.
  • Dropping without checking. DROP TABLE removes the data and any dependent views or foreign keys will block or cascade depending on how you write it. Always inspect first.
  • Forgetting case sensitivity. CREATE TABLE "Users" (quoted) is a different object from users. Mixing quoted and unquoted names is a frequent source of phantom duplicates.
  • Ignoring the schema. A table in public and one in a custom schema can share a name. If your search path puts one first, you may not realise the other exists.
  • Trusting IF NOT EXISTS as a schema check. It only checks the name. If the existing table has an old structure, you will get silent mismatches later.
  • Re-running migrations manually. Running the same SQL script twice is the classic way to hit 42P07 in staging and production.

Tips

  • Wrap schema changes in a transaction (BEGIN; ... COMMIT;) so a failed step leaves the database unchanged.
  • Use CREATE TABLE IF NOT EXISTS in scripts that may run more than once, such as setup or bootstrap scripts.
  • Always qualify object names with the schema in application code and migrations.
  • Keep a naming convention for temporary or versioned tables so a _v2 or _old suffix does not become permanent clutter.
  • Check pg_class if information_schema does not show what you expect: SELECT relname, relnamespace FROM pg_class WHERE relname = 'your_table'; covers tables, views, indexes and sequences, all of which can collide.
  • Remember that CREATE TABLE can also fail with 42P07 if a view or sequence with that name exists — relations share a namespace.

Troubleshooting

The table does not appear in \dt but the error persists. It may be a view, materialised view, sequence or index rather than a plain table. Run \dv, \dm and \ds, or query pg_class as shown above.

You cannot drop the table because of dependencies. PostgreSQL will name the dependent objects. Either drop them first, or use DROP TABLE ... CASCADE — but read the notice carefully, because CASCADE can remove views and foreign keys you still need.

The error comes from an ORM or migration tool. Check the tool's version table (for example flyway_schema_history or alembic_version) to see whether the migration is recorded as applied. If it is not, but the table exists, the schema was changed outside the tool and you need to reconcile the two.

It works in one environment but not another. Compare schemas and search paths between environments. A table created manually in staging but not in production, or vice versa, is a common cause.

You renamed a table and the old name still conflicts. Renaming does not free the old name if a dependent object kept a reference, or if a second table with that name exists in another schema. Re-run the lookup query to find it.

Frequently Asked Questions

What does SQLSTATE 42P07 mean exactly?

It is PostgreSQL's duplicate_table condition: the relation name you tried to create already exists in the target schema. It applies to tables, views, sequences and indexes, since they share a namespace.

Does CREATE TABLE IF NOT EXISTS hide real problems?

It can. It suppresses the error but does not compare the existing table's columns with what you intended, so a stale structure can go unnoticed. Use it for idempotent scripts, not as a substitute for proper migrations.

Can two tables with the same name exist in one database?

Yes, if they are in different schemas. They cannot coexist in the same schema. Quoting also matters: "Orders" and orders are distinct names.

Will dropping the table break my application?

Possibly. Dropping removes the data and can break views, foreign keys and queries that reference it. Back up first and check dependencies with \d before dropping anything in production.

Why did this appear after a deployment?

Usually because a migration ran twice, or because the schema was created manually and the migration tool then tried to create it again. Check the migration history table and reconcile it with the actual schema.

Is 42P07 the same as 42P01?

No. 42P01 is undefined_table — the table does not exist. 42P07 is the opposite: it already does. The two often appear together when a script is run against the wrong database.