Error Encyclopedia

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

1

Inserting a record with an ID that already exists

2

Inserting an email or username that is already registered

3

Race condition where two concurrent requests insert the same value

4

Primary key sequence/auto-increment getting out of sync

5

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: