UNIQUE constraint failed (primary key)
SQLITE_CONSTRAINT_PRIMARYKEY (extended code 1555) is the specific constraint violation raised when an INSERT or UPDATE produces a duplicate value for a column that is declared as the PRIMARY KEY. In Python's sqlite3 module it surfaces as sqlite3.IntegrityError with a message identifying the table and column.
- 1Inserting a row with a primary key value that already exists in the table
- 2Updating a row's primary key to collide with another existing row
- 3Using an integer primary key value that was already issued by an autoincrement sequence
An explicit integer primary key is inserted twice.
import sqlite3
conn = sqlite3.connect(':memory:')
conn.execute('CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT)')
conn.execute("INSERT INTO products VALUES (1, 'Widget')")
conn.execute("INSERT INTO products VALUES (1, 'Gadget')") # triggers 1555expected output
sqlite3.IntegrityError: UNIQUE constraint failed: products.id
Fix
Use AUTOINCREMENT or let SQLite assign rowids
WHEN When primary key values should be assigned automatically.
import sqlite3
conn = sqlite3.connect(':memory:')
conn.execute('CREATE TABLE products (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)')
conn.execute("INSERT INTO products (name) VALUES ('Widget')")
conn.execute("INSERT INTO products (name) VALUES ('Gadget')")
print(conn.execute('SELECT * FROM products').fetchall())Why this works
Without an explicit value for id, SQLite assigns the next available rowid. AUTOINCREMENT additionally guarantees monotonically increasing values — without it, SQLite may reuse a deleted row's id.
✕ Add AUTOINCREMENT to every table by default
AUTOINCREMENT is slower than plain INTEGER PRIMARY KEY because it requires a separate sqlite_sequence table lookup on every insert. Only use it when monotonicity (no id reuse) is a strict requirement.
Extended code 1555 introduced. Earlier versions return the base SQLITE_CONSTRAINT code without distinguishing the constraint type.
sqlite3.h — SQLITE_CONSTRAINT_PRIMARYKEY = 1555
SQLite AUTOINCREMENT documentation ↗Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev