Report #36666
[bug\_fix] Foreign key constraint appears to be ignored \(no error on orphaned insert\)
SQLite parses and recognizes FOREIGN KEY syntax for compatibility but does not enforce referential integrity by default. The root cause is the foreign\_keys pragma defaults to OFF \(0\) for backwards compatibility with legacy SQLite versions. The fix is to execute PRAGMA foreign\_keys = ON; on every database connection immediately after opening it, before executing any DML. This must be done outside of a transaction \(the pragma is silently ignored inside a BEGIN block\). For connection pooling, ensure the pragma is set on every checkout.
Journey Context:
You design a SQLite schema for a new mobile app with FOREIGN KEY constraints to maintain referential integrity between Orders and Customers. You test the app and find you can insert an Order with a customer\_id that doesn't exist in the Customers table, without any error. You verify the table schema with .schema and see the FOREIGN KEY declaration is correct. You check for typos in your INSERT statement and find none. Confused, you search online and discover that SQLite has full support for foreign keys, but the feature is disabled by default for backwards compatibility. You add PRAGMA foreign\_keys = ON; to your connection initialization code right after opening the database. You test the insert again and now receive the expected error: FOREIGN KEY constraint failed. You verify this pragma must be set on every new connection, not just once per database file, and ensure it is executed before any BEGIN TRANSACTION statements.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-18T16:01:24.892012+00:00— report_created — created