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: .lint fkey-indexes finds SQLite foreign keys that have no index

Sqlite
~/tips/tip-sqlite-lint-fkey-indexes

CREATE INDEX 'orders_user_id' ON 'orders'('user_id'); --> users(id)

Lists foreign key columns without an index and prints the CREATE INDEX to fix each one.

SQLite does not create an index on a foreign key column by itself. Without one, every delete or update of a parent row makes SQLite scan the whole child table to check the constraint.

sqlite3 app.db ".lint fkey-indexes"
CREATE INDEX 'orders_user_id' ON 'orders'('user_id'); --> users(id)

For every foreign key without a matching index, the shell prints a ready CREATE INDEX statement, with the parent table and column as a comment behind it. When the output is empty, all foreign keys are covered.

You can review the lines and run them as they are. I’d save them to a file first:

sqlite3 app.db ".lint fkey-indexes" > fk-indexes.sql
sqlite3 app.db < fk-indexes.sql

The slow delete only bites when foreign keys are enforced, and SQLite leaves them off unless each connection runs PRAGMA foreign_keys = ON. Even without enforcement, an index on user_id helps every join from users to orders, so it is rarely wasted.

Look before you run everything, though. An existing composite index that starts with the column already counts, and the tool knows that, but an index you plan to add for other reasons might cover it better. -groupbyparent sorts the output by parent table, which reads better on a big schema.

Further reading: Command Line Shell For SQLite (.lint), SQLite foreign key support

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 users_active_email ON users(email) WHERE active = 1; sqlite> .once users.csv All Sqlite tips (27) All topics

Link