SQLITE_CONSTRAINT_FOREIGNKEY
SQLiteERRORNotableConstraintofficial confidence

FOREIGN KEY constraint failed

Production Risk

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
  1. 1INSERT into a child table with a foreign key value that does not exist in the parent table.
  2. 2DELETE from a parent table when child rows still reference it.
  3. 3Foreign key enforcement not enabled (PRAGMA foreign_keys = ON required).
How to reproduce

INSERT, UPDATE, or DELETE with foreign_keys enabled.

trigger — this will error
trigger — this will error
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 failed

expected output

sqlite3.IntegrityError: FOREIGN KEY constraint failed

Fix 1

Fix 2

Fix 3

What not to do

Version notes

Sources
Official documentation ↗

sqlite3.h — SQLITE_CONSTRAINT_FOREIGNKEY = 787

SQLite foreign keys

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All SQLite errors