# duplicate key value violates unique constraint "pets_pkey"

Source: https://sqlstreak.com/sql/errors/duplicate-key-violates-unique-constraint · Tested on PostgreSQL 18.6 and SQLite 3.54.1; results generated 2026-11-22.


**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

- PostgreSQL: `ERROR: duplicate key value violates unique constraint "pets_pkey"`
- SQLite: `UNIQUE constraint failed: pets.id`

## How PostgreSQL prints it

```
ERROR:  duplicate key value violates unique constraint "pets_pkey"
DETAIL:  Key (id)=(1) already exists.
```

## 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).

## The broken query

```sql
INSERT INTO pets (id, name, species, age, weight_kg, adopted, arrived_on)
VALUES (1, 'Rex', 'dog', 2, 10, false, '2026-01-01');
```

## The fix

```sql
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.

| id | name | species |
| --- | --- | --- |
| 21 | Rex | dog |
