KITFORMA · EDITORIAL ANSWER
Why does SQLite accept a child row whose parent does not exist?
KitForma editorial guide. Foreign-key enforcement must be enabled and verified for each relevant SQLite connection. Declaring a constraint alone should not be treated as proof of enforcement.
Step-by-step answer
PRAGMA foreign_keys = ON at connection initialization before a transaction, then read the setting back. Test an invalid child insert and a parent deletion that should be restricted. Run foreign_key_check when auditing existing data. Enabling enforcement does not automatically repair historical violations. Connection pools and migration tools need the same initialization policy, and changing the pragma inside an active transaction does not provide the intended switch.
Minimal example:
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("PRAGMA foreign_keys = ON")
db.executescript("""
CREATE TABLE parent(id INTEGER PRIMARY KEY);
CREATE TABLE child(parent_id INTEGER REFERENCES parent(id));
""")
try:
db.execute("INSERT INTO child VALUES (?)", (999,))
except sqlite3.IntegrityError:
db.rollback()
else:
raise AssertionError("Missing parent was accepted")
finally:
db.close()Sources and verification
Sources checked:
Scope: This editorial guide is based on the cited sources and tool behavior. A forum question or a query observed for our site does not establish market search volume, low competition, guaranteed rankings or inadequate answers elsewhere.
This editorial answer was prepared by KitForma with AI assistance. It is not presented as a real member question or an independent user review. Check the sources and the result with your own file; report corrections in the discussion.