Why might SQLite accept a foreign-key definition but not enforce it?
Quick answer
SQLite can accept a foreign-key declaration without enforcing it because support must be available in the SQLite build and enforcement must also be enabled at runtime. PRAGMA foreign_keys = ON applies to one connection, so set and check it on every connection your application uses. Do this before starting a transaction, then use a disposable test to check that an unmatched child row is rejected. [S1] [S2]
The question, the details, the next step.
A practical checklist
Enable
PRAGMA foreign_keys = ONon each connection.Set it before starting any transaction or savepoint.
Query
PRAGMA foreign_keyson the same connection and confirm that enforcement is reported as enabled.Treat no result row as a possible unsupported-build signal; investigate the SQLite build.
Use a disposable database and an intentionally unmatched child row to test rejection.
Repeat the verification for connections created by pools, workers, or separate application paths.
A few more useful answers
Does `PRAGMA foreign_keys = ON` enable enforcement for every connection?
No. The setting applies to the connection on which you run it, so set and verify it for each connection. [S1]
Can I turn enforcement on after beginning a transaction?
What if querying `PRAGMA foreign_keys` returns no row?
That can indicate the SQLite build lacks foreign-key support. The pragma result alone does not identify the build configuration, so check the library used by the application. [S1]
Sources
References used for this guide.
- [S1] SQLite foreign-key support: runtime enablement and build requirements sqlite.org · Checked
- [S2] SQLite PRAGMA reference: foreign_keys setting sqlite.org · Checked
