brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: PRAGMA foreign_keys = ON makes SQLite actually enforce foreign keys

Sqlite
~/tips/tip-database-sqlite-pragma-foreign-keys-on

sqlite> PRAGMA foreign_keys = ON;

Turns on foreign key enforcement for a SQLite connection, since it is off by default.

You can declare a FOREIGN KEY in a SQLite table and still delete the parent row it points to without any complaint. I find that surprising for a database, and it is the reason for this tip: enforcement is a setting, and it is not on by default.

sqlite3 app.db
sqlite> PRAGMA foreign_keys;
0
sqlite> PRAGMA foreign_keys = ON;
sqlite> PRAGMA foreign_keys;
1

The docs say that since SQLite 3.6.19 the default is off, that it may change in a future release, and that applications should set the flag they need and not depend on the default. The default can also be changed when SQLite is compiled, so the answer on one machine is not the answer on another. That is why I would ask for the value on each connection.

Two behaviours that catch people out. The pragma is a no-op inside a transaction: enforcement can only be switched when there is no pending BEGIN or SAVEPOINT. And it belongs to the connection. Per the docs it affects all statements prepared on that connection, but a new connection starts again from the default, so the app has to run it every time it connects. Typing it once in the shell does not change the database file.

The caveat for existing data: turning enforcement on is not described as cleaning up rows that already violate a constraint. To find those, SQLite has a second pragma, PRAGMA foreign_key_check;. The docs say it checks the database, or one table, and returns one row for each violated foreign key.

Further reading: SQLite: PRAGMA Statements (foreign_keys)

More Sqlite tips SELECT unixepoch('2026-01-01 00:00:00'); SELECT name, iif(qty > 0, 'in stock', 'sold out') AS state sqlite3 -bail app.db < migrate.sql CREATE INDEX 'orders_user_id' ON 'orders'('user_id'); –> users(id) CREATE INDEX users_active_email ON users(email) WHERE active = 1; All Sqlite tips (27) All topics

Link