sqlstreak

SQL error

relation "pets" already exists / table pets already exists

Updated · Tested on PostgreSQL 18.6 and SQLite 3.54.1 (results generated , re-checked on every release)

Short answer

A table (or view, index or sequence, which PostgreSQL calls relations) with that name already exists. Use CREATE TABLE IF NOT EXISTS, drop the old one first if you mean to replace it, or choose another name.

The exact messages

  • PostgreSQLERROR: relation "pets" already exists
  • SQLitetable pets already exists

How to read this message

This is what PostgreSQL 18.6 prints for the broken query below, the way psql shows it.

ERROR:  relation "pets" already exists

SQLite 3.54.1 reports the same mistake as table pets already exists, with no line number: look for the word or column it names.

Why it happens

Running a setup script twice

The second run meets the tables the first one made. IF NOT EXISTS makes the script safe to re-run.

A name already used by something else

In PostgreSQL, an index or view called pets blocks a table called pets too: they share one namespace per schema.

Reproduce it, then fix it

Both queries run on a real database in your browser. Switch dialects to compare.

Broken
CREATE TABLE pets (id INTEGER PRIMARY KEY, name TEXT);
SELECT 1;
Fixed
CREATE TABLE IF NOT EXISTS pets (id INTEGER PRIMARY KEY, name TEXT);
SELECT COUNT(*) AS pets FROM pets;

IF NOT EXISTS skips the CREATE when the table is there. Careful: it doesn't check the columns, so an old table with a different shape stays as it was.

The fix returns, PostgreSQL: 1 row

pets
20

The fix returns, SQLite: 1 row

pets
20

Experiment with it: PostgreSQL playground·SQLite playground

Another fix

To replace a table (and lose its data), drop it first. DROP … IF EXISTS doesn't fail when it isn't there.

DROP TABLE IF EXISTS pet_notes;
CREATE TABLE pet_notes (id INTEGER PRIMARY KEY, note TEXT);
SELECT COUNT(*) AS notes FROM pet_notes;

Returns, PostgreSQL: 1 row

notes
0

Returns, SQLite: 1 row

notes
0

Official documentation

Stop hitting this error

Practise the concept behind it in a five-minute lesson, or read the full guide: SQL CREATE TABLE, constraints and views.