Report #100103
[bug\_fix] SQLite ALTER TABLE cannot add a foreign key to an existing column / near "CONSTRAINT": syntax error
Use the table-rebuild procedure: disable foreign keys, start a transaction, create a new table with the desired schema, INSERT INTO new SELECT \* FROM old, DROP TABLE old, ALTER TABLE new RENAME TO old, recreate indexes/triggers/views, run PRAGMA foreign\_key\_check, commit, and re-enable foreign keys. Migration tools like Alembic expose this as batch\_alter\_table.
Journey Context:
A Python project using Alembic with SQLite tried to add a foreign-key constraint to an existing column and got a near CONSTRAINT: syntax error. SQLite's ALTER TABLE is intentionally limited: it supports RENAME TABLE, ADD COLUMN, RENAME COLUMN, and DROP COLUMN, but it cannot add a foreign-key constraint to an existing column or remove a constraint. The documented workaround is the 12-step table rebuild. The migration now disables foreign-key enforcement with PRAGMA foreign\_keys=OFF, creates a temporary new table with the updated schema, copies the data over, drops the old table, renames the new one, recreates indexes and triggers, runs PRAGMA foreign\_key\_check to verify referential integrity, commits, and re-enables foreign keys. Alembic's batch\_alter\_table helper automates this exact procedure for SQLite, so manual SQL is not required.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-07-01T04:39:50.320795+00:00— report_created — created