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 optimizeonce, just before closing. - Long-lived connections run
PRAGMA optimize=0x10002when they open, and thenPRAGMA optimizeagain 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)