SQLite Foreign Keys: Enable Enforcement and Find Orphan Rows
Fix SQLite foreign keys that are not enforced. Verify each connection, avoid transaction timing traps and audit existing data with foreign_key_check.
A REFERENCES clause describes a relationship, but your SQLite connection must also enforce it. Set PRAGMA foreign_keys=ON before starting a transaction, read the setting back, and initialize every writer connection. Enabling enforcement does not repair existing orphan rows. This guide separates schema, connection policy, transaction timing and data auditing with an executable Python lab using invented temporary data.
A declared relationship can still have an unprotected writer
A child table may correctly declare that parent_id references parent(id), yet an import inserts an ID with no parent. The schema alone does not tell you what enforcement setting the importing connection used. A successful insert is therefore a reason to inspect the actual connection and transaction, not immediately rewrite the relationship.
The lab opens two connections to one temporary database. Connection a explicitly enables foreign keys; connection b explicitly disables them to reproduce an unsafe writer. The same database file then has one protected writer and one unprotected writer. The difference is intentional and does not depend on the SQLite build’s default setting.
In application code, place connection initialization where new connections are created. A pool, background worker or migration runner can introduce another connection with a different policy. Checking one interactive SQL console cannot establish what the application’s other writers will do.
Source: SQLite: Foreign key support, enabling and deferred constraints ↗
Enable and verify before the transaction begins
Run PRAGMA foreign_keys=ON and then query PRAGMA foreign_keys on that same connection. The expected readback is a row containing 1. Do not depend on a default that may differ by build configuration, and do not treat the lack of an exception as proof that a PRAGMA changed anything.
The setting cannot be changed while a transaction is pending. The lab tests both directions: trying to enable it after BEGIN leaves it disabled, and trying to disable it after BEGIN leaves it enabled. Both statements execute without making the requested policy change. That is why the readback and transaction boundary belong in the same diagnosis.
Use the transaction API your driver actually exposes. In this lab, isolation_level=None leaves SQLite in its autocommit mode between explicit SQL BEGIN and COMMIT statements. This makes the boundaries visible. A framework or another Python transaction mode can begin a transaction earlier than the surrounding code suggests.
-- Run on each new connection, before BEGIN or application writes.
PRAGMA foreign_keys = ON;
PRAGMA foreign_keys; -- Expect one row: 1
PRAGMA foreign_key_list(child);
PRAGMA foreign_key_check; -- No rows means no reported FK violations.Source: SQLite: PRAGMA foreign_keys, foreign_key_check and integrity_check ↗
Separate foreign-key policy from nullability and uniqueness
The fixture parent uses an INTEGER PRIMARY KEY. The child uses its own primary key and a nullable parent_id that references the parent key. A child referencing ID 1 succeeds; a child referencing missing ID 999 is rejected on the protected connection. The rejected row does not appear in the table afterward.
A NULL child key is a separate case. In this single-column relationship, the nullable child key permits NULL without requiring a matching parent. If every child must name a parent, declare the child column NOT NULL as well. The deferred fixture includes NOT NULL and checks that NULL is rejected even though its foreign-key check is deferred.
For another schema, verify that the referenced parent columns form an appropriate primary or unique key, including relevant collation requirements. An error such as foreign key mismatch points toward the relationship definition rather than merely an absent parent row. Compare the stored schema and foreign_key_list output before changing production data.
The child-parent index in the lab is a practical schema choice for relationship lookups. Its presence is not what activates enforcement, and the lab does not benchmark index performance. Correctness checks and indexing decisions should be reviewed separately.
Source: SQLite: Foreign key support, enabling and deferred constraints ↗
Enabling checks does not clean up old data
Connection b inserts child row 10 referencing missing parent 999 while enforcement is disabled. Connection a can then detect that orphan with PRAGMA foreign_key_check. Enabling enforcement on b afterward does not remove the orphan or make its reference valid; the next audit still reports it.
For this fixture, foreign_key_check returns (child, 10, parent, 0). The columns identify the child table, the offending rowid, the parent table and the foreign-key constraint ID. That last ID maps to the first column from foreign_key_list(child). Here the child’s INTEGER PRIMARY KEY makes rowid 10 easy to identify. A WITHOUT ROWID child table reports NULL in that position.
The chosen fixture repair inserts the missing parent and reruns the audit. That is suitable only because the invented data defines that parent as legitimate. In a real import, the right repair might be correcting a child reference, restoring a real parent or rejecting the source record. Do not create placeholder parents merely to silence the report.
Source: SQLite: PRAGMA foreign_keys, foreign_key_check and integrity_check ↗
An integrity check and a relationship audit answer different questions
The database with the deliberately inserted orphan still returns ok from PRAGMA integrity_check in the lab. That result does not contradict the foreign-key violation. SQLite’s integrity check does not report foreign-key errors; use foreign_key_check for those relationships.
For a migration or import review, record both the writer’s enforcement state and the relationship audit result. One describes the policy for writes through a connection; the other describes violations visible to the checking statement. Neither alone establishes that all future writers will use the correct configuration.
An empty foreign_key_check result is not an audit of every business rule. It does not prove that amounts, dates, authorization or required relationships outside declared constraints are correct. Use it as a specific relationship check, with its result interpreted at the transaction and data state where it ran.
| Observation | What it establishes | What to check next |
|---|---|---|
| foreign_keys returns 1 | This connection has enforcement enabled | Every other writer and transaction boundary |
| foreign_key_list shows a relationship | The table declares that reference | Actual enforcement and parent-key definition |
| foreign_key_check returns rows | Declared references are violated | Map rowid/constraint ID and choose a valid repair |
| integrity_check returns ok | That integrity check found no reported issue | Run the separate foreign-key audit |
Source: SQLite: PRAGMA foreign_keys, foreign_key_check and integrity_check ↗
A deferred foreign key can fail at COMMIT
The second fixture uses DEFERRABLE INITIALLY DEFERRED. Inside a transaction, inserting its child before the parent is temporarily allowed. foreign_key_check can see the unresolved relationship before commit. Trying COMMIT while the parent is still missing raises an integrity error.
The lab then verifies that the transaction remains open. It inserts the legitimate parent into that same transaction and commits successfully. In another case, it chooses ROLLBACK after the failed commit and verifies that the pending child row disappears. Your application needs an explicit response to that failure; catching the exception does not by itself complete the transaction.
Deferral changes when a constraint must be satisfied, rather than disabling the relationship. This lab uses a declared deferred foreign key and does not toggle PRAGMA defer_foreign_keys. It also does not generalize the timing to every referential action, nested savepoint or driver transaction mode.
Source: SQLite: Foreign key support, enabling and deferred constraints ↗
Run the complete local enforcement lab
Save this program as sqlite_fk_lab.py and run python3 sqlite_fk_lab.py. It requires Python 3.12 or later with its sqlite3 module. The exact published program was executed with Python 3.12.14 linked to SQLite 3.53.1. Its final line was PASS: 28 checks; SQLite 3.53.1. Another supported build prints its own linked SQLite version.
The first fixture creates a database in a temporary directory, opens two connections, and closes both in finally before directory cleanup. The second uses a separate in-memory database. All records are invented. No existing database is opened, and there are no network calls or external packages.
The deliberately disabled connection is a counterexample for learning, not an import recommendation. The tests check both settings explicitly, rejected writes, nullable keys, protected parent deletion, an orphan audit, integrity_check, constraint-ID mapping, transaction no-ops and deferred commit repair or rollback.
"""Python 3.12+ standard library; disposable invented SQLite data."""
import sqlite3
import tempfile
from pathlib import Path
checks = 0
def check(condition, label):
global checks
checks += 1
if not condition:
raise AssertionError(label)
def scalar(c, sql):
return c.execute(sql).fetchone()[0]
def fk(c):
row = c.execute('PRAGMA foreign_keys').fetchone()
if row is None:
raise RuntimeError('Foreign-key enforcement is unavailable in this build')
return row[0]
def rejects(c, sql, parameters=(), message='FOREIGN KEY'):
try:
c.execute(sql, parameters)
except sqlite3.IntegrityError as error:
check(message in str(error), 'expected constraint diagnostic')
else:
raise AssertionError('Expected rejection: ' + sql)
SCHEMA = '''
CREATE TABLE parent(id INTEGER PRIMARY KEY);
CREATE TABLE child(id INTEGER PRIMARY KEY,
parent_id INTEGER REFERENCES parent(id));
CREATE INDEX child_parent_idx ON child(parent_id);
INSERT INTO parent VALUES(1);
'''
def main():
with tempfile.TemporaryDirectory(prefix='sqlite-fk-lab-') as directory:
path = Path(directory) / 'lab.db'
# Explicit SQL BEGIN/COMMIT controls transactions in this lab.
a = sqlite3.connect(path, isolation_level=None)
b = sqlite3.connect(path, isolation_level=None)
try:
a.execute('PRAGMA foreign_keys=ON')
b.execute('PRAGMA foreign_keys=OFF') # Intentionally unsafe fixture.
check(fk(a) == 1 and fk(b) == 0, 'two connection-local settings')
a.executescript(SCHEMA)
a.execute('INSERT INTO child VALUES(1,1)')
rejects(a, 'INSERT INTO child VALUES(2,999)')
check(scalar(a, 'SELECT count(*) FROM child') == 1, 'failed row absent')
a.execute('INSERT INTO child VALUES(3,NULL)')
check(scalar(a, 'SELECT count(*) FROM child WHERE parent_id IS NULL') == 1,
'nullable child key is permitted')
rejects(a, 'DELETE FROM parent WHERE id=1')
check(scalar(a, 'SELECT count(*) FROM parent') == 1, 'parent delete rejected')
b.execute('INSERT INTO child VALUES(10,999)')
check(a.execute('PRAGMA foreign_key_check').fetchall() ==
[('child', 10, 'parent', 0)], 'orphan from unprotected writer detected')
check(a.execute('PRAGMA integrity_check').fetchall() == [('ok',)],
'integrity_check does not cover foreign-key violations')
relation = a.execute('PRAGMA foreign_key_list(child)').fetchone()
check(relation[:5] == (0, 0, 'parent', 'parent_id', 'id'), 'map violation ID')
b.execute('PRAGMA foreign_keys=ON')
check(fk(b) == 1, 'enable second connection outside transaction')
check(len(b.execute('PRAGMA foreign_key_check').fetchall()) == 1,
'enabling does not repair old orphan')
rejects(b, 'INSERT INTO child VALUES(11,998)')
a.execute('INSERT INTO parent VALUES(999)') # Chosen fixture repair.
check(a.execute('PRAGMA foreign_key_check').fetchall() == [], 'repair rechecked')
b.execute('PRAGMA foreign_keys=OFF')
b.execute('BEGIN')
b.execute('PRAGMA foreign_keys=ON')
check(fk(b) == 0, 'enabling inside transaction is no-op')
b.execute('INSERT INTO child VALUES(12,777)')
check(len(b.execute('PRAGMA foreign_key_check').fetchall()) == 1,
'transaction can contain an orphan while disabled')
b.execute('ROLLBACK')
b.execute('PRAGMA foreign_keys=ON')
check(fk(b) == 1, 'enable after rollback')
b.execute('BEGIN')
b.execute('PRAGMA foreign_keys=OFF')
check(fk(b) == 1, 'disabling inside transaction is also no-op')
rejects(b, 'INSERT INTO child VALUES(12,777)')
b.execute('ROLLBACK')
check(a.execute('PRAGMA foreign_key_check').fetchall() == [], 'rollbacks leave clean data')
finally:
a.close()
b.close()
c = sqlite3.connect(':memory:', isolation_level=None)
try:
c.execute('PRAGMA foreign_keys=ON')
check(fk(c) == 1, 'deferred fixture enforcement enabled')
c.executescript('''CREATE TABLE p(id INTEGER PRIMARY KEY);
CREATE TABLE d(id INTEGER PRIMARY KEY, p_id INTEGER NOT NULL,
FOREIGN KEY(p_id) REFERENCES p(id) DEFERRABLE INITIALLY DEFERRED);''')
c.execute('BEGIN')
c.execute('INSERT INTO d VALUES(1,20)')
check(len(c.execute('PRAGMA foreign_key_check').fetchall()) == 1,
'deferred violation visible before commit')
rejects(c, 'COMMIT')
check(c.in_transaction, 'failed deferred commit keeps transaction open')
c.execute('INSERT INTO p VALUES(20)')
c.execute('COMMIT')
check(not c.in_transaction, 'repaired transaction committed')
check(c.execute('PRAGMA foreign_key_check').fetchall() == [], 'deferred repair verified')
rejects(c, 'INSERT INTO d VALUES(2,NULL)', message='NOT NULL')
c.execute('BEGIN')
c.execute('INSERT INTO d VALUES(3,30)')
rejects(c, 'COMMIT')
c.execute('ROLLBACK')
check(scalar(c, 'SELECT count(*) FROM d') == 1, 'explicit rollback removes pending row')
finally:
c.close()
print(f'PASS: {checks} checks; SQLite {sqlite3.sqlite_version}')
if __name__ == '__main__':
main()A short investigation for “foreign keys are not working”
Start with the connection that performed the unexpected write. Query its enforcement setting before the next transaction and confirm the initializer is actually called. If the application hides connections behind an ORM or pool, inspect the connection-creation hook and test a newly created writer through the normal application path.
Next, identify the transaction state when the setting was issued. The lab demonstrates why a setup statement placed inside an already-running transaction can look successful while leaving the old policy active. Do not commit or roll back unrelated work just to change the setting; fix initialization for the next appropriate transaction boundary.
Finally, inspect the relationship and the data. Distinguish a NULL reference from an orphan, a schema mismatch from a missing parent, and immediate statement failure from deferred commit failure. Run the targeted audit after an intentional repair, then retain a regression that reproduces the original writer and transaction path.
Carry the connection contract into the real application
The useful invariant is that every writer begins application work with the expected enforcement state. Testing only the schema creation script misses a later connection. Testing only an enabled connection misses data imported by a disabled one. The two-connection fixture makes that gap visible with a small deterministic example.
Before using this pattern in a live migration, adapt the transaction boundaries to the actual driver and confirm the backup, repair and deployment procedure for that database. The lab does not exercise concurrency, pools, attached databases, composite keys, cascades or a framework’s lifecycle hooks.
Keep declaration, enforcement and auditing as separate checks: define the relationship correctly, enable it on each writer before transactions, and audit existing rows. When all three are visible in code and tests, a passing insert or a successful integrity check is much less likely to create false confidence.
Your next steps
- Enable and read back foreign_keys on every writer before a transaction begins.
- Use foreign_key_check for existing relationship violations; integrity_check is not a substitute.
- Handle deferred COMMIT failures explicitly: repair within the open transaction or roll it back.
Sources & official resources
Linked resources checked on 2026-11-02. Technical behavior and provider guidance can change; check the documentation for the version you use.
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →