PostgreSQLERROR 23505
PostgreSQL: Duplicate Key Value Violates Unique Constraint
PostgreSQL 23505 is thrown when an INSERT or UPDATE would create a duplicate value in a column or combination of columns covered by a UNIQUE or PRIMARY KEY constraint.
Example Query
INSERT INTO users (email) VALUES ('alice@example.com');
-- Fails if that email already existsCommon Causes
- 1Inserting a row with a primary key value that already exists
- 2Two concurrent transactions inserting the same unique value
- 3Data import with duplicate records in the source file
How to Fix It
Use INSERT … ON CONFLICT DO NOTHING or ON CONFLICT DO UPDATE (upsert) to handle duplicates gracefully. Check for existing records before inserting. Ensure sequences are in sync with the max existing id after data imports.
Need a reliable database?
Try Supabase — free PostgreSQL with a generous free tier. No credit card required.
Got a query causing this error?
Paste it into SQLbuddy and get an instant plain-English explanation with optimization tips.
Analyze My Query →