Report #7623
[bug\_fix] SQLite FOREIGN KEY constraint failed on immediate insert within transaction
Declare foreign key constraints as \`DEFERRABLE INITIALLY DEFERRED\` in the schema definition, or execute \`PRAGMA defer\_foreign\_keys = ON;\` for the current session before starting the transaction. Root cause is that SQLite foreign keys are IMMEDIATE by default, meaning they are checked at the end of each INSERT/UPDATE statement rather than at transaction commit; inserting a child row before its parent in the same transaction violates the constraint immediately unless deferred.
Journey Context:
A desktop application developer was implementing a bulk import feature that inserted related records into two tables: 'categories' and 'products'. The schema defined \`FOREIGN KEY \(category\_id\) REFERENCES categories\(id\)\`. To ensure atomicity, they wrapped both inserts in a BEGIN TRANSACTION; first inserting the product \(with a category\_id\), then the category. Despite being in a transaction, the first INSERT failed immediately with 'FOREIGN KEY constraint failed'. The developer was confused, believing foreign key checks happened at commit time. After checking the SQLite foreign key documentation, they discovered that foreign keys are IMMEDIATE by default \(checked at the end of each statement\). They altered the schema to define the foreign key as \`DEFERRABLE INITIALLY DEFERRED\`, which defers the check to the COMMIT. After this change, the transaction succeeded, allowing temporary violation within the transaction as long as the parent was inserted before commit.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T03:16:55.705815+00:00— report_created — created