Skip to content
Back to the playbook

Handling D1 UNIQUE constraint violations

Cloudflare D1revision 1

Diagnostic tree

  1. In progressINSERT throws UNIQUE constraint failed / SQLITE_CONSTRAINTA write to a table with a UNIQUE column or index (often the primary business key, like user_id or email) fails with D1_ERROR: UNIQUE constraint failed.
View the whole map (7 more steps)
  • Confirm a row with that value already exists
  • Treat the duplicate as an update, or ignore it deliberately
  • Check whether this is a check-then-insert race
  • Stop pre-checking; let the constraint be the source of truth
  • Not a duplicate-row issue — escalate
  • Re-run the insert path against a duplicate value
  • Resolved

What to test

INSERT throws UNIQUE constraint failed / SQLITE_CONSTRAINT

A write to a table with a UNIQUE column or index (often the primary business key, like user_id or email) fails with D1_ERROR: UNIQUE constraint failed.

What happened?