Free: 4 trials of 20 minutes, no cardStart free

Craftstack Academy
SQL

SQLite: UNIQUE constraint failed, and how to fix it

· 9 min read

Your sign-up form saves new users. The first one works. The second time someone uses the same email, the program stops:

Terminal
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.email

UNIQUE 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:

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: table users, column email.

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:

sql
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:

sql
INSERT INTO users (id, email, name) VALUES (1, 'mia@example.com', 'Mia');
Error (SQLite)
UNIQUE constraint failed: users.id

Row 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:

sql
INSERT INTO users (email, name) VALUES ('mia@example.com', 'Mia');

The same happens with a TEXT PRIMARY KEY, like a product code:

Error (SQLite)
UNIQUE constraint failed: t2.code

Cause 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":

sql
CREATE TABLE enrollments (student TEXT, course TEXT, UNIQUE(student, course));
INSERT INTO enrollments VALUES ('Alex', 'SQL');
INSERT INTO enrollments VALUES ('Alex', 'SQL');
Error (SQLite)
UNIQUE constraint failed: enrollments.student, enrollments.course

The 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:

sql
CREATE TABLE t3 (email TEXT);
INSERT INTO t3 VALUES ('x'), ('x');
CREATE UNIQUE INDEX idx_email ON t3(email);
Error (SQLite)
UNIQUE constraint failed: t3.email

Find and clean the duplicates first:

sql
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:

sql
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:

sql
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:

python
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.com was accepted next to sam@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 (PostgreSQL)
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 table or no 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 UNIQUE from the table. The error stops, and your table fills up with duplicates that break every count and every login.
  • INSERT OR REPLACE for 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

  1. Read the table and column after failed:.
  2. Find the existing row with SELECT ... WHERE column = value.
  3. 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?
  4. Choose the behaviour: skip (INSERT OR IGNORE), update (ON CONFLICT ... DO UPDATE), or tell the user (catch IntegrityError).
  5. 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'.

  1. INSERT INTO tags VALUES ('sql');
  2. INSERT OR IGNORE INTO tags VALUES ('sql');
  3. 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

  1. Read the table and column after failed:.
  2. Find the existing row with the same value.
  3. Don't set INTEGER PRIMARY KEY ids by hand.
  4. Decide: skip, update or tell the user.
  5. 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.

1 beginner error a week

One common error, what it means and how to fix it, in a short email. Free, and you can unsubscribe in any email.

SQL

PostgreSQL ERROR: column does not exist, and how to fix it

Why PostgreSQL says ERROR: column "x" does not exist: double quotes around text, capital letters in names, an alias in WHERE, or a typo. How to read the HINT and fix each, with real output.

Error explained · · 8 min read

SQL

SQL error: ambiguous column name, and how to fix it

Why SQLite says ambiguous column name: id and PostgreSQL says column reference "id" is ambiguous after a JOIN, and how table aliases fix it in SELECT, WHERE, ORDER BY and GROUP BY. With real output.

Error explained · · 9 min read

SQL

SQLite error: no such table, and how to fix it

Why SQLite says no such table (sqlite3.OperationalError: no such table): a typo, a table never created, or the wrong database file, often a new empty one. How to check and fix each, with real output.

Error explained · · 9 min read

Learn by writing the code yourself.

Twenty minutes with the tutor, right in your browser. No card, nothing to install.

Start the free trial
A session: the tutor's chat on the left, the code editor with a Java program and its output on the right