Your sign-up form saves new users. The first one works. The second time someone uses the same email, the program stops:
Traceback (most recent call last):
File "main.py", line 5, in <module>
db.execute("INSERT INTO users (email, name) VALUES (?, ?)", ("sam@example.com", name))
~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
sqlite3.IntegrityError: UNIQUE constraint failed: users.emailUNIQUE constraint failed: users.email means you tried to store a value in the email column of the users table that is already there, and that column is marked UNIQUE: no two rows may have the same value. SQLite refused the new row to protect that rule. The message tells you exactly which table and column: here users.email. So the question is never what went wrong, it's why your program tried to insert a duplicate, and what it should do instead. This article covers the usual causes and the three standard fixes.
Try it yourself
Save this as main.py and run python main.py:
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT UNIQUE, name TEXT)")
for name in ["Sam", "Sam"]:
db.execute("INSERT INTO users (email, name) VALUES (?, ?)", ("sam@example.com", name))The first insert works, and the second gives the error above.
What the error means
A constraint is a rule on a table that the database enforces for you. UNIQUE says that every value in that column must be different. A PRIMARY KEY is unique too.
Read the message in parts:
sqlite3.IntegrityError: the error is about the integrity of your data. A rule would be broken.UNIQUE constraint failed: the broken rule is "unique".users.email: tableusers, columnemail.
This is the database doing its job. You almost never want to remove the rule. You want to decide what should happen when a duplicate arrives.
Cause 1: the value really is a duplicate
The example above. Someone signs up twice, or a form is submitted twice, or a list you import has the same item twice. Before choosing a fix, find the existing row:
SELECT * FROM users WHERE email = 'sam@example.com';Then decide what you want: keep the old row, replace it, update it, or tell the user. Each of these has a standard fix, shown below.
Cause 2: setting the id by hand
When you give a primary key value yourself, it's common to reuse one by mistake:
INSERT INTO users (id, email, name) VALUES (1, 'mia@example.com', 'Mia');UNIQUE constraint failed: users.idRow 1 already exists. If the column is INTEGER PRIMARY KEY, leave it out of the INSERT, and SQLite chooses the next free number for you:
INSERT INTO users (email, name) VALUES ('mia@example.com', 'Mia');The same happens with a TEXT PRIMARY KEY, like a product code:
UNIQUE constraint failed: t2.codeCause 3: running a setup script twice
You have a script that creates tables and inserts some starting rows. It works the first time. The second time, the tables still exist (if you used CREATE TABLE IF NOT EXISTS), and every starting row is now a duplicate.
Three ways out:
- Make the inserts safe to repeat with
INSERT OR IGNORE(fix 1 below). - Reset on purpose: delete the database file before the setup runs, during development.
- Check first: insert the starting rows only if the table is empty.
Cause 4: a unique combination of columns
A table can require that a combination is unique, for example "a student can enrol in each course only once":
CREATE TABLE enrollments (student TEXT, course TEXT, UNIQUE(student, course));
INSERT INTO enrollments VALUES ('Alex', 'SQL');
INSERT INTO enrollments VALUES ('Alex', 'SQL');UNIQUE constraint failed: enrollments.student, enrollments.courseThe message lists both columns. Alex in SQL and Alex in Python are fine; Alex in SQL twice is not.
Cause 5: adding a UNIQUE rule to data that already has duplicates
If you create a unique index on a column that already contains the same value twice, the index itself fails:
CREATE TABLE t3 (email TEXT);
INSERT INTO t3 VALUES ('x'), ('x');
CREATE UNIQUE INDEX idx_email ON t3(email);UNIQUE constraint failed: t3.emailFind and clean the duplicates first:
SELECT email, COUNT(*) FROM t3 GROUP BY email HAVING COUNT(*) > 1;This lists every value that appears more than once. If GROUP BY and HAVING are new to you, see GROUP BY errors.
Fix 1: ignore duplicates with INSERT OR IGNORE
When a duplicate should be skipped, for example a list of tags or a repeated setup:
INSERT OR IGNORE INTO users (email, name) VALUES ('sam@example.com', 'Ignored');No error, and no change: the existing row stays as it was. Use it only when skipping is really what you want, because it hides the duplicate silently.
Fix 2: update the existing row with ON CONFLICT
When a duplicate should update the existing row (an "upsert"), say so:
INSERT INTO users (email, name) VALUES ('sam@example.com', 'Sam new')
ON CONFLICT(email) DO UPDATE SET name = excluded.name;excluded.name means "the value from the row you tried to insert". In our test, after this statement, the existing row kept id 1 and its name became Sam new.
(INSERT OR REPLACE also exists, but it deletes the old row and inserts a new one, which can change its id and break links from other tables. ON CONFLICT ... DO UPDATE changes the row in place.)
Fix 3: catch the error and tell the user
For a sign-up form, the right answer is usually a message: "This email is already registered". Catch the specific error:
try:
db.execute("INSERT INTO users (email, name) VALUES (?, ?)", (email, name))
db.commit()
except sqlite3.IntegrityError:
print("This email is already registered.")Catch sqlite3.IntegrityError specifically, not every error, so real bugs still show up.
Duplicates that UNIQUE doesn't catch
Two things surprise people, both checked in SQLite:
- Different capital letters are different values.
SAM@example.comwas accepted next tosam@example.com. - A trailing space is a different value.
'sam@example.com '(with a space, 16 characters) was accepted next to the 15-character version.
So for emails, clean the value before saving: email.strip().lower() in Python. Or declare the column email TEXT UNIQUE COLLATE NOCASE, so SQLite compares it without regard to capitals.
And NULL is not a duplicate of NULL: in our test, two users without an email were both accepted. If every user must have an email, add NOT NULL to the column too.
The same error in PostgreSQL
PostgreSQL words it differently, and names the constraint instead of the column:
ERROR: duplicate key value violates unique constraint "users_email_key"
DETAIL: Key (email)=(sam@example.com) already exists.The DETAIL line is very useful: it shows the exact value that already exists. For a primary key, the constraint is called users_pkey. PostgreSQL also supports ON CONFLICT (email) DO NOTHING and DO UPDATE, with the same meaning as in SQLite. (MySQL says Duplicate entry 'sam@example.com' for key ....)
Errors that look alike
NOT NULL constraint failed: users.email: a required value is missing, rather than repeated.FOREIGN KEY constraint failed: a row points to another table's row that doesn't exist (when foreign keys are switched on).no such tableorno such column: the table or column name is wrong. See SQLite: no such table and no such column.
Wrong fixes that don't help
- Removing
UNIQUEfrom the table. The error stops, and your table fills up with duplicates that break every count and every login. INSERT OR REPLACEfor everything. It can give rows new ids and silently drop data in other columns.- Catching every exception with a bare
except:. A typo in your SQL would look like "email already registered".
A debugging walkthrough
- Read the table and column after
failed:. - Find the existing row with
SELECT ... WHERE column = value. - Ask why your code inserts it again: a form submitted twice, a setup script run twice, an id set by hand, an import with repeated rows?
- Choose the behaviour: skip (
INSERT OR IGNORE), update (ON CONFLICT ... DO UPDATE), or tell the user (catchIntegrityError). - Clean the values (trim, lowercase) before saving, so near-duplicates don't slip through.
Practice
What happens? The table is CREATE TABLE tags (name TEXT UNIQUE) and already has 'sql'.
INSERT INTO tags VALUES ('sql');INSERT OR IGNORE INTO tags VALUES ('sql');INSERT INTO tags VALUES ('SQL');
Answers. (1) UNIQUE constraint failed: tags.name. (2) No error, no new row. (3) Accepted: capitals make it a different value, unless the column uses COLLATE NOCASE.
Frequently asked questions
What does "UNIQUE constraint failed" mean in SQLite?
You tried to insert or update a row so that a column marked UNIQUE (or a primary key) would contain the same value twice. The message names the table and column.
How do I insert only if the row doesn't exist?
INSERT OR IGNORE INTO ... in SQLite, or INSERT ... ON CONFLICT DO NOTHING, which also works in PostgreSQL.
How do I update a row if it already exists?
INSERT ... ON CONFLICT(column) DO UPDATE SET col = excluded.col.
How do I find duplicate values in a column?
SELECT col, COUNT(*) FROM t GROUP BY col HAVING COUNT(*) > 1;
Why does UNIQUE allow two NULL values?
In SQL, NULL means "unknown", and two unknowns aren't considered equal. Add NOT NULL if the value is required.
A quick checklist
- Read the table and column after
failed:. - Find the existing row with the same value.
- Don't set
INTEGER PRIMARY KEYids by hand. - Decide: skip, update or tell the user.
- Clean values (trim, lowercase) before saving.
For a method that works on any error, read how to read an error message. The SQLite documentation describes UPSERT and conflict handling.
