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 optimize lets SQLite refresh its statistics only where it needs to

Sqlite
~/tips/tip-database-sqlite-pragma-optimize

sqlite3 app.db "PRAGMA optimize;"

Updates SQLite's query planner statistics only for tables where that is likely to help.

SQLite plans queries better when it has statistics about your tables, which come from ANALYZE. Running a full ANALYZE on a large database is slow, so most people never do. PRAGMA optimize is the cheap version that decides for itself what is worth doing.

sqlite3 app.db "PRAGMA optimize;"

The docs say it is usually a no-op or nearly so and very fast. When it does need to run ANALYZE on some tables, it sets a temporary analysis limit, so that run cannot take too long. Their recommendation depends on how the application uses the connection:

  • Short-lived connections run PRAGMA optimize once, just before closing.
  • Long-lived connections run PRAGMA optimize=0x10002 when they open, and then PRAGMA optimize again now and then, say once a day.
  • After a schema change, especially a CREATE INDEX, run it as well.

The mask in the second line adds the 0x10000 bit, which makes it check the size of all tables and not just the recently used ones. The 0x00002 bit is the part that runs ANALYZE and is on by default.

Before you trust it on a database you care about, you can ask what it would do: PRAGMA optimize=0x00001; is debug mode, which does nothing and returns a line of text for each optimization it would have made.

The caveat is that the docs say the details of what it does are expected to change over time. It is a good default for an app, but I would not build a script around a specific output. And it is for query plans: it does not shrink the file, which is the job of VACUUM.

Further reading: SQLite: PRAGMA Statements (optimize)

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