SQL error
duplicate key value violates unique constraint "pets_pkey"
Updated · Tested on PostgreSQL 18.6 and SQLite 3.54.1 (results generated , re-checked on every release)
Short answer
You're inserting a value that already exists in a column that must be unique (here the primary key id). Use a new value, let the database generate ids, or use an upsert (ON CONFLICT).
The exact messages
- PostgreSQLERROR: duplicate key value violates unique constraint "pets_pkey"
- SQLiteUNIQUE constraint failed: pets.id
How to read this message
This is what PostgreSQL 18.6 prints for the broken query below, the way psql shows it. DETAIL says more about what went wrong.
ERROR: duplicate key value violates unique constraint "pets_pkey" DETAIL: Key (id)=(1) already exists.
SQLite 3.54.1 reports the same mistake as UNIQUE constraint failed: pets.id, with no line number: look for the word or column it names.
Why it happens
Inserting an id that's taken
Hard-coding ids is fragile. Let the database generate them: GENERATED ALWAYS AS IDENTITY (or SERIAL) in PostgreSQL, INTEGER PRIMARY KEY in SQLite.
An out-of-sync sequence after an import
If rows were inserted with explicit ids, PostgreSQL's sequence may still hand out old numbers. Reset it: SELECT setval(pg_get_serial_sequence('pets', 'id'), MAX(id)) FROM pets;
You meant to update existing rows
Use INSERT … ON CONFLICT (id) DO UPDATE SET … (works in PostgreSQL and SQLite).
Reproduce it, then fix it
Both queries run on a real database in your browser. Switch dialects to compare.
INSERT INTO pets (id, name, species, age, weight_kg, adopted, arrived_on)
VALUES (1, 'Rex', 'dog', 2, 10, false, '2026-01-01');INSERT INTO pets (id, name, species, age, weight_kg, adopted, arrived_on)
VALUES (21, 'Rex', 'dog', 2, 10, false, '2026-01-01');
SELECT id, name, species FROM pets WHERE id = 21;Id 21 is free, so the insert succeeds (the SELECT shows the new row). Nothing persists here: every run starts from a fresh copy.
The fix returns, PostgreSQL: 1 row
| id | name | species |
|---|---|---|
| 21 | Rex | dog |
The fix returns, SQLite: 1 row
| id | name | species |
|---|---|---|
| 21 | Rex | dog |
Experiment with it: PostgreSQL playground·SQLite playground
Official documentation
Stop hitting this error
Practise the concept behind it in a five-minute lesson, or read the full guide: SQL INSERT, UPDATE and DELETE.