Practical technical guides / Core IT: databases (SQLite foreign keys)

SQLite Ignores Your Foreign Keys Until Each Connection Turns Them On

Measured in SQLite 3.49.1: foreign keys are off by default, the pragma is per connection and ignored inside a transaction, and Python autocommit=False hides it.

By Sandeep Belgavi · Published 2026-11-14

Measured in SQLite 3.49.1: foreign keys are off by default, the pragma is per connection and ignored inside a transaction, and Python autocommit=False hides it.

A schema that looks enforced

Dinky's team keeps Belgavi's Book Store order history in SQLite: a book_order table and an order_line table whose order_id column declares REFERENCES book_order(id) ON DELETE CASCADE. The schema reads like a promise that no order line can point at an order that does not exist, and that deleting an order removes its lines. On a default connection, neither is true.

SQLite parses foreign key clauses and stores them in the schema, but it only enforces them on connections where PRAGMA foreign_keys is on, and it is off by default. The SQLite documentation states this plainly, and explains it as backwards compatibility: enforcement arrived in version 3.6.19, and turning it on by default would have broken applications that already had violating data. Every measurement below was made in Python 3.13.5 with its bundled SQLite 3.49.1, on synthetic orders.

What a default connection does

import sqlite3
con = sqlite3.connect(':memory:')
con.executescript("""
CREATE TABLE book_order (id INTEGER PRIMARY KEY, customer TEXT NOT NULL);
CREATE TABLE order_line (
  id INTEGER PRIMARY KEY,
  order_id INTEGER NOT NULL REFERENCES book_order(id) ON DELETE CASCADE,
  isbn TEXT NOT NULL);
""")
print(con.execute('PRAGMA foreign_keys').fetchone())          # (0,)
con.execute("INSERT INTO order_line VALUES (1, 999, 'x')")     # no error: order 999 does not exist
con.execute("INSERT INTO book_order VALUES (7, 'Jenya')")
con.execute("INSERT INTO order_line VALUES (2, 7, 'y')")
con.execute('DELETE FROM book_order WHERE id = 7')
print(con.execute('SELECT COUNT(*) FROM order_line WHERE order_id = 7').fetchone())   # (1,)

The orphan insert succeeds, and the cascade does nothing: the line for order 7 survives its order. With PRAGMA foreign_keys = ON executed first on the same kind of connection, the orphan insert raises sqlite3.IntegrityError: FOREIGN KEY constraint failed and the delete removes the line.

Four ways enforcement stays off

1. The pragma is per connection. It is not stored in the database file. In the companion, connection A turns it on; connection B opened on the same file reads 0 and inserts an orphan without complaint. Every process, every pool member, every migration tool and every ad hoc shell session must turn it on.

2. The pragma is a no-op inside a transaction. The documentation says so, and the measurement agrees: after BEGIN; PRAGMA foreign_keys = ON; the setting still reads 0, an orphan insert succeeds, and the setting is still 0 after COMMIT. There is no error; the statement is silently ignored.

3. Python's autocommit=False keeps a transaction open. Since Python 3.12, sqlite3.connect(..., autocommit=False) gives PEP 249 behaviour: a transaction is opened implicitly and reopened after every commit and rollback. A PRAGMA foreign_keys = ON executed on such a connection therefore always lands inside a transaction and is ignored. The companion measures 0 with in_transaction true. With autocommit=True, or with the default legacy mode, which does not open a transaction before a PRAGMA, the same statement turns enforcement on. Set it before choosing transaction behaviour, or pass it through a connection factory that runs it first.

4. A build can omit it. SQLite compiled with SQLITE_OMIT_FOREIGN_KEY parses the clauses and never enforces them, and PRAGMA foreign_keys then returns no row at all. Bundled Python and most distributions include support, but checking the return value catches the exception.

Turning it on safely in application code

def open_db(path: str) -> sqlite3.Connection:
    con = sqlite3.connect(path, autocommit=True)       # no implicit transaction yet
    con.execute('PRAGMA foreign_keys = ON')
    row = con.execute('PRAGMA foreign_keys').fetchone()
    if row is None or row[0] != 1:
        raise RuntimeError('SQLite foreign key enforcement is unavailable or off')
    con.autocommit = False                              # PEP 249 transactions from here on
    return con

Reading the value back is the important line. It turns three silent failures, a transaction already open, a build without support, and a wrapper that swallowed the statement, into a startup error. The same check belongs in health probes for long-lived services, because a pool can hand out connections created by a different code path.

ORMs and connection pools

An ORM usually owns connection creation, so the pragma has to go into its connection hook rather than into application code. The SQLAlchemy documentation for SQLite says the PRAGMA foreign_keys = ON statement must be emitted on all connections before use, including the initial MetaData.create_all() call, and shows a connect event listener that does it. Its example also handles the trap measured above: it temporarily sets the driver connection's autocommit to True before executing the pragma, with a comment that the sqlite3 driver will not set it when autocommit=False, and restores the previous setting afterwards.

from sqlalchemy import event
from sqlalchemy.engine import Engine

@event.listens_for(Engine, "connect")
def enable_sqlite_fks(dbapi_connection, connection_record):
    previous = dbapi_connection.autocommit
    dbapi_connection.autocommit = True          # a pragma inside a transaction is ignored
    cursor = dbapi_connection.cursor()
    cursor.execute("PRAGMA foreign_keys=ON")
    cursor.execute("PRAGMA foreign_keys")
    assert cursor.fetchone()[0] == 1
    cursor.close()
    dbapi_connection.autocommit = previous

The read-back assertion is an addition to the documented pattern, for the same reason as before. The same documentation warns that with foreign keys enabled, emitting CREATE or DROP for tables that reference each other needs care, so schema tools may need their own handling.

Existing data is not checked when you turn it on

Enabling enforcement does not validate rows already in the database. In the companion, a database with three orphan lines still holds all four lines after the pragma is turned on. SQLite only checks a constraint when a statement changes the relevant columns: updating the ISBN of an orphan line succeeds, while updating its order_id to another missing order fails.

Find the violations explicitly:

PRAGMA foreign_key_check;               -- every violation in every table
PRAGMA foreign_key_check(order_line);   -- one table

Each result row names the child table, the rowid of the offending row, the parent table, and the index of the foreign key in the child table. For the companion's three orphans it returns order_line with rowids 2, 3 and 4 and parent book_order. Run it in CI against a copy of production data, and before any migration that enables enforcement.

Deferred constraints

By default a violation fails the statement that causes it. A constraint declared DEFERRABLE INITIALLY DEFERRED is checked at COMMIT instead, which lets you insert a child before its parent within one transaction. The companion shows both sides: child first, then parent, then commit succeeds; child with no parent, then commit fails with FOREIGN KEY constraint failed, and the transaction is still open afterwards. Your code must then roll back or fix the data; a retry of COMMIT alone fails again. PRAGMA defer_foreign_keys = ON defers all constraints for the current transaction, which is useful for bulk loads that arrive out of order.

Index the child key

Enforcement makes parent deletes and key updates look up matching child rows. Without an index on order_line(order_id), each parent delete scans the child table. The SQLite documentation recommends indexing child key columns for this reason; the companion's schema includes the index.

Migrating a database that has been running without enforcement

  1. Add the open-and-verify function above to every code path that opens the database, including scripts and tests, and fail fast when the read-back is not 1.
  2. On a copy of production data, run PRAGMA foreign_key_check and count the violations per table.
  3. Decide per violation: restore the missing parent, delete the orphan, or move it to a quarantine table for a person to review. Do it in a migration you can rerun.
  4. Index every child key column that lacks one.
  5. Add a test that opens a connection the way production does and asserts an orphan insert fails. This is the test that would have caught all four failure paths above.
  6. Turn enforcement on in production, then run foreign_key_check again on a schedule; it should stay empty.

Failure modes

  • A migration tool that opens its own connection without the pragma, so the cascade silently stops working during migrations.
  • An ORM event hook that sets the pragma after the first statement opened a transaction.
  • ON DELETE CASCADE relied on for cleanup, tested on an enforced connection, and run in production on one that is not.
  • Data repaired once and violated again by a batch job that bypasses the application.

Verification

Run the companion: python example.py prints every probe, and python -m unittest -v test_example.py asserts the default-off result, enforcement and cascade when on, the no-op inside a transaction, the Python autocommit=False case, per-connection scope, the check of existing orphans, and deferred commit failure. Results depend on the SQLite build; the recording used 3.49.1.

Limits

These are behaviours of SQLite's foreign key implementation as documented and as measured on one build. Other databases enforce foreign keys by default, and their deferral rules differ.

Primary references and authorship

Original explanation and synthetic examples by Sandeep Belgavi. Companion code: Sandeep-BA/agent-decision-lab/examples/python/sqlite_foreign_key_enforcement. Views are my own and do not represent any employer, past or present.