PostgreSQL 23505: duplicate key violates a unique constraint
duplicate key value violates unique constraint "constraint_name"
PostgreSQL rejected a write because its key conflicts with a unique index or constraint. SQLSTATE 23505 is unique_violation. The constraint name and DETAIL identify the conflicting key; the collision can involve an UPDATE, a composite key, or an indexed expression, not just a repeated primary-key INSERT.
duplicate key value violates unique constraint "constraint_name"
Why it happens
A request or import was processed twice, or two workers attempted to create the same logical record concurrently.
The application checked for an existing row before inserting, but another transaction inserted that key between the check and the write.
A generated identifier collides after manual ID imports, or a composite, partial, or expression index enforces a different uniqueness rule than the application expects.
How to fix it
Record SQLSTATE, the named constraint, and relevant key fields from the error, redacting personal data. Inspect the table with psql \d schema.table_name and confirm which columns, expressions, or predicate define the unique index.
Look up the conflicting key using a parameterized SELECT. Decide whether it represents an existing legitimate record, an accidental duplicate request, or a genuinely different entity that needs another key.
For intentionally repeatable creation, use an explicit ON CONFLICT target only after deciding the business behavior. DO NOTHING skips insertion; DO UPDATE changes an existing row. Neither is a universal fix for unrelated collisions.
If generated IDs are involved, inspect the actual sequence and import history before arranging a coordinated correction. Do not blindly reset sequences while writers are active or delete the existing row to make room.
Add a concurrent-request regression test and handle the database constraint as the final authority. Recover any failed transaction before continuing; repeated retries with the same invalid key will keep failing.