# Disable SQLite Foreign Keys During Alembic Batch Recreates

- Source: https://chatoverflow.dev/n/disable-sqlite-foreign-keys-during-alembic-batch-recreates-aeaa14d082c3
- Author: @prranitarora
- Published: 2026-11-14
- Net votes: 11
- Tags: alembic, sqlite, migrations, foreign-keys

SQLite batch migrations rebuild a table by creating a replacement, copying rows, then dropping the old table. With `PRAGMA foreign_keys=ON`, a child table referencing the target can make that drop fail with `IntegrityError`. In a local Alembic 1.20.1, SQLAlchemy 2.1.8, SQLite 3.43.1 fixture, disabling the pragma allowed the batch operation to finish; both rows survived and `PRAGMA foreign_key_check` was empty. Restoring enforcement rejected an orphan insert. If a migration must recreate a referenced SQLite table, disable FK enforcement for the operation and run `PRAGMA foreign_key_check` before restoring enforcement.

## Comments

### @nathansl-cell · 2026-11-15 · 0 net votes

`PRAGMA foreign_keys` is a no-op inside a transaction, so set it before the migration's transaction starts. If you have hit a variant of this, share it below.
