Duplicate Key Constraint Violation Error
Fix 'duplicate key value violates unique constraint' errors in PostgreSQL, MySQL, and other databases when inserting duplicate data.
What Does This Error Mean?
The 'duplicate key value violates unique constraint' error means you are trying to insert a record with a value that already exists in a column with a UNIQUE constraint. This applies to primary keys, unique indexes, and columns with the UNIQUE constraint.
Common Causes
Inserting a record with an ID that already exists
Inserting an email or username that is already registered
Race condition where two concurrent requests insert the same value
Primary key sequence/auto-increment getting out of sync
Upsert (INSERT ... ON CONFLICT) not used when it should be
How to Fix It
Use INSERT ... ON CONFLICT (PostgreSQL)
Specify what to do when a conflict occurs — DO NOTHING or DO UPDATE.
-- Insert or do nothing INSERT INTO users (id, email, name) VALUES (1, 'john@example.com', 'John') ON CONFLICT (email) DO NOTHING; -- Insert or update (upsert) INSERT INTO users (id, email, name) VALUES (1, 'john@example.com', 'John') ON CONFLICT (email) DO UPDATE SET name = EXCLUDED.name;
Use INSERT IGNORE (MySQL)
Ignore duplicate key errors silently.
INSERT IGNORE INTO users (id, email, name) VALUES (1, 'john@example.com', 'John');
Check for existing records first
Query for duplicates before inserting.
const existing = await db.query(
"SELECT id FROM users WHERE email = $1",
[email]
)
if (existing.rows.length > 0) {
return { error: "Email already registered" }
}
await db.query(
"INSERT INTO users (email, name) VALUES ($1, $2)",
[email, name]
)Related Tools
Use these tools to debug and fix this error:
Related Errors
Other common errors in this category:
401 Unauthorized Error
Learn what a 401 Unauthorized error means, common causes, and how to fix authentication failures in your web applications.
403 Forbidden Error
Learn what 403 Forbidden means, how it differs from 401, and how to fix access denied errors in your applications.
404 Not Found Error
Learn what 404 Not Found means, common causes, and how to fix broken links and missing resources on your website or API.
429 Too Many Requests Error
Learn what 429 Too Many Requests means, how rate limiting works, and how to handle or avoid hitting API rate limits.