PostgreSQL Duplicate Key Violates Unique Constraint: Fix Error 23505
By Sharon Ben-Moshe · September 5, 2026 · 2 min read
Sharon Ben-Moshe is the founder of sqlfmt, a browser-based SQL formatter and validator with misspelled-keyword suggestions across PostgreSQL, MySQL, SQLite, SQL Server, and BigQuery.
Troubleshoot and fix PostgreSQL Error 23505: duplicate key value violates unique constraint. Learn how to fix desynced sequences and use ON CONFLICT.
Quick answer
PostgreSQL error 23505 occurs when an INSERT or UPDATE violates a UNIQUE or PRIMARY KEY constraint. If caused by manually inserted IDs desyncing an auto-increment sequence, fix it by advancing the sequence with SELECT setval(pg_get_serial_sequence('table', 'id'), max(id)) FROM table. To handle application-level duplicates gracefully, use INSERT ... ON CONFLICT DO NOTHING or DO UPDATE.
FAQs
What is SQLSTATE 23505 in PostgreSQL?
SQLSTATE 23505 represents unique_violation. PostgreSQL throws it whenever an operation attempts to create a row whose indexed columns match an existing row under a UNIQUE index or PRIMARY KEY constraint.
Why does an auto-increment sequence produce duplicate key errors?
Sequences do not check the table for existing maximum values. If rows were inserted with explicit ID values (e.g. during a migration or database restore), the sequence counter remains behind the maximum ID in the table. The next nextval() call will collide with an existing row.
How do I ignore duplicate key errors on insert?
Add `ON CONFLICT (constraint_columns) DO NOTHING` to your INSERT statement. PostgreSQL will skip conflicting rows silently without aborting the transaction.
Can ON CONFLICT update the existing row instead of failing?
Yes. Use `ON CONFLICT (constraint_columns) DO UPDATE SET col = EXCLUDED.col`. This is known as an UPSERT and guarantees atomic updates without concurrency race conditions.
Keep reading
Fix BigQuery "Unrecognized Name" Error: Scoping and Syntax Rules
By Sharon Ben-Moshe · Sep 29, 2026
Fix Google BigQuery's "Unrecognized name: column" error. Learn alias visibility rules across WHERE and QUALIFY, case sensitivity, and struct unnesting.
Read postSQLite "Datatype Mismatch" (Error 20): Type Affinity and Strict Tables
By Sharon Ben-Moshe · Sep 26, 2026
Understand SQLite Error 20 (datatype mismatch). Learn how SQLite type affinity, CHECK constraints, and STRICT tables enforce data integrity.
Read postTry it now
Paste your SQL into sqlfmt — format, validate, and catch typos free in your browser.