Skip to content

Unique constraint violation: duplicate key

Quick summary

You tried to insert a duplicate value in a column with a unique constraint — the database rejects the operation.

Why this happens

  • The application tried to insert a row with a key that already exists in the table

  • A race condition caused two concurrent inserts to try the same key simultaneously

  • An update changed a column value to one that already exists in another row

Minimal example

✗ Broken code
await db.query('INSERT INTO users (email, name) VALUES ($1, $2)', ['[email protected]', 'John']);
// Error: duplicate key value violates unique constraint on email
✓ Fixed code
await db.query(
  'INSERT INTO users (email, name) VALUES ($1, $2) ON CONFLICT (email) DO UPDATE SET name = EXCLUDED.name',
  ['[email protected]', 'John']
); // upsert: insert or update if exists

Using ON CONFLICT DO UPDATE turns the insert into an upsert, handling the duplicate key by updating the existing row instead of failing.

How to diagnose

  • Check the error message for the constraint name and the duplicate value

  • Query the table to confirm the duplicate value already exists

  • Review the insert/update logic to understand why a duplicate was attempted

How to fix

  • Use INSERT ON CONFLICT DO NOTHING or INSERT ... ON DUPLICATE KEY UPDATE to handle duplicates gracefully

  • Check for existence before inserting, or use upsert/merge statements

  • Generate unique keys with a sequence or UUID to avoid collisions

How to prevent

  • Use upsert patterns (ON CONFLICT, ON DUPLICATE KEY UPDATE) for idempotent inserts

  • Generate unique identifiers with database sequences or UUIDs instead of application logic

Related Resources

Related Glossary

Related Lessons

← Back to language