duplicate key value violates unique constraint
This error occurs when you try to insert or update a row with a value that already exists in a column with a UNIQUE constraint.
The duplicate key value violates unique constraint error occurs when inserting or updating data that would create a duplicate in a unique column.
Understanding the Error
ERROR: duplicate key value violates unique constraint "users_email_key"
DETAIL: Key (email)=(user@example.com) already exists.
PostgreSQL enforces uniqueness and rejects any operation that would create duplicates.
Common Causes
1. Inserting Duplicate Data
SQL
2. Primary Key Collision
SQL
3. Bulk Import Conflicts
Importing data that contains duplicates or conflicts with existing records.
How to Fix It
Solution 1: Use ON CONFLICT (Upsert)
SQL
Solution 2: Use ON CONFLICT DO NOTHING
SQL
Solution 3: Check Before Insert
SQL
Solution 4: Use Transactions with Exception Handling
SQL
Solution 5: Let PostgreSQL Generate IDs
SQL
Best Practices
- Use ON CONFLICT for upsert operations
- Use SERIAL/IDENTITY for auto-generated primary keys
- Add UNIQUE constraints during table design, not after
- Validate data before bulk imports
- Handle exceptions in application code