Fix "UNIQUE constraint failed" in SQLite
Why SQLite says UNIQUE constraint failed, how to find the duplicate, and when to use ON CONFLICT DO UPDATE, INSERT OR IGNORE or INSERT OR REPLACE.
Quick Answer
You inserted or updated a row with a value that already exists in a column that must be unique. The message names the column, for example UNIQUE constraint failed: users.email. Find the existing row, then decide whether the new row should update it, be skipped or fail:
-- the row that already has the value
SELECT * FROM users WHERE email = 'a@example.com';
-- update it instead of failing (SQLite 3.24+)
INSERT INTO users (email, name) VALUES ('a@example.com', 'Ana')
ON CONFLICT (email) DO UPDATE SET name = excluded.name;
Use INSERT OR IGNORE to skip duplicates silently. Be careful with INSERT OR REPLACE: it deletes the old row and inserts a new one.
What the error means
A UNIQUE column, a PRIMARY KEY or a unique index already holds the value you tried to write. SQLite rejects the statement with SQLITE_CONSTRAINT (code 19) and changes nothing. The extended code tells you which kind of key it was:
| Client | What you see |
|---|---|
| sqlite3 CLI | Error: stepping, UNIQUE constraint failed: users.email (19) |
| Python sqlite3 | sqlite3.IntegrityError: UNIQUE constraint failed: users.email, e.sqlite_errorname == "SQLITE_CONSTRAINT_UNIQUE" |
| Node better-sqlite3 | SqliteError: UNIQUE constraint failed: users.email, err.code === "SQLITE_CONSTRAINT_UNIQUE" |
A composite key lists every column, for example UNIQUE constraint failed: users.tenant, users.name. The value itself is never shown, so you have to look it up.
In VisuaLeaf
Find the unique columns and the duplicate in VisuaLeaf
Open the .db file in VisuaLeaf, right-click the table and choose Tables Info. The Schema tab lists the primary key and every index, with the unique ones marked, so you can see exactly which columns the error is about. Show DDL shows the full CREATE TABLE and CREATE UNIQUE INDEX statements, including expression indexes such as lower(email).
Then, in the SQL editor next to it, find values that already appear more than once, for example when you're about to add a unique index to existing data:
SELECT email, COUNT(*) FROM users
GROUP BY email HAVING COUNT(*) > 1;
See Table Management.

What we found testing this
- Primary keys report as "UNIQUE constraint failed" too. Inserting a duplicate
idgaveUNIQUE constraint failed: users.id. Only the extended code differs:SQLITE_CONSTRAINT_PRIMARYKEYinstead ofSQLITE_CONSTRAINT_UNIQUE. INSERT OR REPLACEchanged the row's id. Replacinga@x.comwith an explicit id of 99 deleted the old row (id 1) and inserted a new one, so anything pointing at id 1 lost its row.ON CONFLICT ... DO UPDATEkept id 1 and only changedname.- NULLs never collide. Two rows with
email = NULLwere both accepted by aUNIQUEcolumn. - A
TEXT PRIMARY KEYaccepted two NULLs. This is a long-standing SQLite quirk: onlyINTEGER PRIMARY KEYandWITHOUT ROWIDtables force primary keys to be non-null. AddNOT NULLyourself. - Uniqueness is case-sensitive by default. A
TEXT UNIQUEcolumn accepted both'A'and'a'. UseCOLLATE NOCASEon the column or a unique index onlower(col)if those should count as duplicates. INSERT OR IGNOREhides more than duplicates.changes()returned 0 with no error, and rows that broke aNOT NULLorCHECKconstraint were dropped silently too.INSERT OR REPLACEdoesn't fire delete triggers by default. AnAFTER DELETEtrigger logged nothing when a row was replaced, untilPRAGMA recursive_triggers = ON.
Choose how duplicates should be handled
| You want | Use | Watch out for |
|---|---|---|
| Update the existing row | INSERT ... ON CONFLICT (col) DO UPDATE SET ... | The target must match a unique index, or you get "ON CONFLICT clause does not match any PRIMARY KEY or UNIQUE constraint" |
| Keep the existing row | INSERT OR IGNORE or ON CONFLICT DO NOTHING | Also silently skips rows that break NOT NULL or CHECK constraints |
| Replace the row entirely | INSERT OR REPLACE | Deletes the old row and gives it a new rowid. Delete triggers fire only with PRAGMA recursive_triggers = ON |
| Fail and tell the user | Catch the error | Check the extended code, not the message text |
import sqlite3
try:
conn.execute("INSERT INTO users (email) VALUES (?)", (email,))
except sqlite3.IntegrityError as e:
if e.sqlite_errorname == "SQLITE_CONSTRAINT_UNIQUE": # Python 3.11+
print("That email is already registered")
else:
raise
try {
db.prepare('INSERT INTO users (email) VALUES (?)').run(email)
} catch (err) {
if (err.code === 'SQLITE_CONSTRAINT_UNIQUE') { /* duplicate */ } else throw err
}
Common causes
- Inserting your own ids. Copying rows between databases or re-running a seed script brings the old ids with it. Leave
idout of the insert and let SQLite assign one. - Running an import twice. Make the import idempotent with
ON CONFLICT DO NOTHINGorDO UPDATE. - Double-submitted forms or retries. Two identical requests both pass a "does it exist?" check, then the second insert fails. Let the unique constraint do the check and handle the error.
- An
UPDATEthat collides. Changingemailto a value another row already has fails the same way.
Don't fix this by dropping the unique index. The constraint is usually the only thing stopping duplicate accounts or double-counted orders.
Frequently Asked Questions
What does "UNIQUE constraint failed" mean in SQLite?
A UNIQUE column, PRIMARY KEY or unique index already contains the value you tried to insert or update. The message names the column, for example users.email. The statement is rejected and nothing is changed.
How do I insert a row only if it does not exist in SQLite?
Use INSERT OR IGNORE, or INSERT ... ON CONFLICT DO NOTHING. Both skip the row without an error when a unique column already has that value.
What is the difference between INSERT OR REPLACE and ON CONFLICT DO UPDATE?
INSERT OR REPLACE deletes the existing row and inserts a new one, so the rowid can change and columns you did not supply are reset. ON CONFLICT DO UPDATE updates the existing row in place and keeps its id.
Can a UNIQUE column contain several NULL values in SQLite?
Yes. NULL is never equal to another NULL, so a UNIQUE column accepts any number of NULLs. Add NOT NULL if empty values should not be allowed.