Why it happens: UNIQUE rejects a duplicate value
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
email TEXT NOT NULL UNIQUE
);
INSERT INTO customers (id, email)
VALUES (1, 'amy@example.test');
INSERT INTO customers (id, email)
VALUES (2, 'amy@example.test');The second row tries to reuse the same email address. If the email identifies a customer uniquely, the constraint is doing its job: the problem lies in the data or the operation, not in UNIQUE.
How to fix it in SQL
SELECT id, email
FROM customers
WHERE email = 'amy@example.test';| id | |
|---|---|
| 1 | amy@example.test |
Then decide what you meant to do: update the existing customer, fix the email on the new row, or use a different key if the domain genuinely allows duplicates. Do not drop the constraint just to make the error go away.
How to check it
Query every column of the unique key; for a composite key, check the whole combination.
How to avoid it next time
Do not drop UNIQUE to hide an identity conflict.
Related cases worth checking
This guide covers non-null duplicates. The rules for NULL inside unique constraints differ between engines. PostgreSQL, for example, allows several null values in a unique constraint by default and offers NULLS NOT DISTINCT to change that behaviour. SQLite also treats null values as distinct when checking UNIQUE. If your problem includes NULL, check the engine's documentation and the page on UNIQUE.
Choosing a policy for the second write
The rejection confirms that a uniqueness rule exists; it does not say what the application should do with the second request. It might be a duplicate record, a retry of the same operation or a legitimate update. Decide whether to return the existing record, change it through a dedicated operation or report a conflict. Removing the constraint so the write goes through changes the data model.
Check every column of the key. In a composite constraint on customer and external reference, repeating a reference for another customer may be valid while repeating the same pair is not. A message about a particular key may not refer to the primary identifier. Also check the collation: two strings that differ only in case can count as equal under the chosen settings.
Checking before inserting does not, on its own, prevent a race between two sessions: both can see that the value is missing and then write it. The constraint remains the real guarantee, and the application must handle the conflict consistently. Do not assume nulls follow the same policy on every engine. If the email is required and unique, also state that it must be present and normalised, rather than leaving both rules to UNIQUE.
Technical questions: SQLite: CREATE TABLE and constraints (opens in a new tab).