How to Fix PostgreSQL Duplicate Key Value Violates Unique Constraint Error
In this tutorial, you'll learn about How to Fix PostgreSQL Duplicate Key Value Violates Unique Constraint Error. We cover key concepts, practical examples, and best practices.
The Problem
You run an INSERT and PostgreSQL returns:
ERROR: duplicate key value violates unique constraint "users_pkey"
DETAIL: Key (id)=(42) already exists.
Or:
ERROR: duplicate key value violates unique constraint "users_email_key"
DETAIL: Key (email)=(user@example.com) already exists.
You attempted to insert a row that conflicts with an existing unique constraint.
Quick Fix
1. Use ON CONFLICT (upsert)
PostgreSQL supports ON CONFLICT to handle duplicates gracefully:
-- Wrong — throws error on duplicate
INSERT INTO users (email, name) VALUES ('user@example.com', 'User');
-- Right — do nothing on conflict
INSERT INTO users (email, name) VALUES ('user@example.com', 'User')
ON CONFLICT (email) DO NOTHING;
-- Right — update on conflict
INSERT INTO users (email, name, last_login) VALUES ('user@example.com', 'User', NOW())
ON CONFLICT (email) DO UPDATE SET
name = EXCLUDED.name,
last_login = EXCLUDED.last_login;
2. Use ON CONFLICT with a unique index
For constraints that are not named, specify the columns:
INSERT INTO users (tenant_id, email, name)
VALUES (1, 'user@example.com', 'User')
ON CONFLICT (tenant_id, email) DO UPDATE SET
name = EXCLUDED.name;
3. Fix sequence gaps after restore
Primary key duplicate errors often come from sequence values being behind the actual max ID after a restore:
-- Check the sequence value vs max id
SELECT MAX(id) FROM users;
SELECT nextval('users_id_seq');
-- Fix the sequence
SELECT setval('users_id_seq', (SELECT MAX(id) FROM users));
4. Remove duplicate data first
If duplicates exist and should not, remove them before adding a constraint:
-- Find duplicates
SELECT email, COUNT(*) FROM users GROUP BY email HAVING COUNT(*) > 1;
-- Delete duplicates keeping the smallest id
DELETE FROM users
WHERE id NOT IN (
SELECT MIN(id) FROM users GROUP BY email
);
Then add the unique constraint.
5. Check application-level deduplication
Prevent duplicates at the application level before inserting:
# Wrong — blindly insert
cursor.execute("INSERT INTO users (email, name) VALUES (%s, %s)", (email, name))
# Right — check first
cursor.execute("SELECT id FROM users WHERE email = %s", (email,))
if not cursor.fetchone():
cursor.execute("INSERT INTO users (email, name) VALUES (%s, %s)", (email, name))
Prevention
- Use
ON CONFLICT DO UPDATEorON CONFLICT DO NOTHINGfor upsert operations. - Reset sequences after any restore that modifies primary key values.
- Add application-level validation before insert operations.
- Monitor PostgreSQL logs for duplicate key errors.
Common Mistakes with duplicate key
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
These mistakes appear frequently in real-world POSTGRES code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro