pgref.dev/sqlite/errors/SQLITE_CONSTRAINT_FOREIGNKEY
SQLITE_CONSTRAINT_FOREIGNKEYERRORTier 2 — Caution⚠️ MEDIUM confidence

FOREIGN KEY constraint failed

Category: ConstraintVersions: 3.6.19+

🔴 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

  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
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
sqlite3.IntegrityError: FOREIGN KEY constraint failed

Fix 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

⚙️ This error reference was generated with AI assistance and reviewed for accuracy. Examples are provided to illustrate common scenarios and may not cover every case. Always test fixes in a development environment before applying to production. Spotted an error? Suggest a correction →