SQLITE_CONSTRAINT_FOREIGNKEYERRORTier 2 — Caution⚠️ MEDIUM confidenceFOREIGN KEY constraint failed
🔴 Production Risk Error
Medium — referential integrity violation; INSERT/DELETE fails.
What this means
SQLITE_CONSTRAINT_FOREIGNKEY (787) is returned when a foreign key constraint is violated — either inserting a child row with no matching parent, or deleting a parent row that has existing children.
Why it happens
- 1INSERT into a child table with a foreign key value that does not exist in the parent table.
- 2DELETE from a parent table when child rows still reference it.
- 3Foreign key enforcement not enabled (PRAGMA foreign_keys = ON required).
How to reproduce
INSERT, UPDATE, or DELETE with foreign_keys enabled.
import sqlite3
conn = sqlite3.connect(':memory:')
conn.execute('PRAGMA foreign_keys = ON')
conn.execute('CREATE TABLE users(id INTEGER PRIMARY KEY)')
conn.execute('CREATE TABLE orders(user_id INTEGER REFERENCES users(id))')
try:
conn.execute('INSERT INTO orders VALUES(999)')
except sqlite3.IntegrityError as e:
print(e) # FOREIGN KEY constraint failedFix 1
Why this works
Enable foreign keys first: PRAGMA foreign_keys = ON
Fix 2
Why this works
Ensure the parent row exists before inserting the child row.
Fix 3
Why this works
Use ON DELETE CASCADE or ON DELETE SET NULL if child deletion should cascade.
What not to do
Why it's wrong:
Version notes
Sources
📚 Official docs: https://www.sqlite.org/rescode.html#constraint_foreignkey
🔧 Source ref: sqlite3.h — SQLITE_CONSTRAINT_FOREIGNKEY = 787
📖 Further reading: SQLite foreign keys
Confidence assessment
⚠️ MEDIUM confidence
Stable.
See also
🔗 Related errors
📄 Reference pages