# Postgres error 23505: duplicate key value violates unique constraint "x_pkey"

> The row would duplicate a value that a primary key or unique index requires to be unique.

Source: https://scribase.com/postgres-errors/23505

SQLSTATE class: Integrity Constraint Violation. Over PostgREST/supabase-js this maps to HTTP 409.

## Causes

- Inserting a row whose key already exists, often a retried request or a double-clicked submit.
- An identity or serial sequence behind the real maximum id after data was copied in with explicit ids, so new inserts reuse old ids.
- Two concurrent transactions inserting the same natural key.

## Fixes

- Use an upsert when a duplicate is expected: insert ... on conflict (key) do update or do nothing.
- After loading data with explicit ids, move the sequence past the maximum.
- Handle the error as a normal outcome in the app (for example "this email is already registered").

## Example

```sql
-- sequence behind after an import
select setval(pg_get_serial_sequence('orders', 'id'), (select max(id) from orders));

-- idempotent insert
insert into subscriptions (user_id, plan) values ($1, $2)
on conflict (user_id) do update set plan = excluded.plan;
```

PostgREST answers 409 Conflict. With supabase-js, .upsert() sends ON CONFLICT for you; pass onConflict when the unique key is not the primary key.