skip to content

In SQLite, what do ANALYZE and the sqlite_stat1 table give the query planner, and how should an app run PRAGMA optimize?

level: middleimportance: should knowfreq 42%

answer

  1. guesses versus measured shape
  2. rows per key prefix
  3. statistics never refresh themselves
  4. optimize at close, 0x10002 at open

basics

~20 s

ANALYZE scans each index and stores row counts and average duplicates per key prefix in sqlite_stat1, which the planner uses to choose indexes and join order. Statistics never refresh by themselves, so apps run PRAGMA optimize, which re-analyzes only tables that need it.

solid answer

~40 s

Without statistics SQLite guesses the shape of the data, for example that each value in an index's left-most column has about 10 duplicates, and it never uses a skip-scan. `ANALYZE` writes one `sqlite_stat1` row per index, such as `20000 5000 10`: 20,000 rows, about 5,000 per city, about 10 per city and surname. Those numbers are not maintained as data changes. The recommended routine is `PRAGMA optimize`: a short-lived connection runs it just before closing; a long-lived one runs `PRAGMA optimize=0x10002` when it opens and plain `PRAGMA optimize` periodically; everyone runs it after `CREATE INDEX`. It is usually a no-op, and since 3.46.0 it limits how long any ANALYZE it triggers can run. A phone's bundled SQLite may predate that, so check the version before copying the advice.

code

console · 13 lines
console
sqlite> CREATE TABLE contacts(id INTEGER PRIMARY KEY, surname TEXT NOT NULL, city TEXT);
sqlite> CREATE INDEX contacts_city_surname ON contacts(city, surname);
sqlite> WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i+1 FROM n WHERE i<20000)
   ...> INSERT INTO contacts(surname, city) SELECT 'S' || (i % 2000), 'C' || (i % 4) FROM n;
sqlite> EXPLAIN QUERY PLAN SELECT id FROM contacts WHERE surname = 'S5';
QUERY PLAN
`--SCAN contacts
sqlite> ANALYZE;
sqlite> SELECT * FROM sqlite_stat1;
contacts|contacts_city_surname|20000 5000 10
sqlite> EXPLAIN QUERY PLAN SELECT id FROM contacts WHERE surname = 'S5';
QUERY PLAN
`--SEARCH contacts USING COVERING INDEX contacts_city_surname (ANY(city) AND surname=?)

go deeper

for a junior

Remember that ANALYZE stores statistics in sqlite_stat1, that they go stale as data changes, and that PRAGMA optimize is the routine way to refresh them.

for a middle

Read a sqlite_stat1 stat string, explain the planner's fallback guesses, and state the open, close and after-CREATE INDEX advice for PRAGMA optimize.

for a senior

Diagnose a plan that changed after data grew: compare sqlite_stat1 with reality, re-run ANALYZE, and allow for a bundled SQLite older than 3.46.0.

for a principal

Decide between adaptive statistics on every install and frozen, tested statistics shipped with the app, and own the reproducibility versus adaptability trade.

## What the planner knows without statistics SQLite's **query planner** picks, for every statement, which index to use for each table and in which order to nest the tables of a join. To compare plans it needs to estimate how many rows each step returns. With no statistics it falls back on fixed guesses: - It assumes each value in the left-most column of an index has an average of **10 duplicates**. - It never chooses a **skip-scan**, which uses an index whose left-most column is not constrained. A skip-scan pays off only at about 18 or more duplicates per left-most value, and only statistics can show that. - When deciding whether to build a temporary index for a join, it assumes a table holds about **one million rows**. These guesses work for many schemas. They fail when the data has an unusual shape, such as a `city` column with four values across 20,000 contacts. ## What ANALYZE writes `ANALYZE` reads every index (or the one schema, table or index you name) and stores the results in `sqlite_stat1`, an internal table with three columns: `tbl`, `idx` and `stat`. Running it is never required; it helps when queries have several plausible plans. | `stat` field | Meaning | |---|---| | first integer | Approximate number of rows in the index | | second integer | Average rows sharing one value of the first index column | | N-th integer | Average rows sharing one value of the first N-1 columns | | `sz=NNN`, `unordered`, `noskipscan` | Optional tokens: average row size, or a ban on range-and-sort use or on skip-scan | So `contacts|contacts_city_surname|20000 5000 10` says 20,000 rows, about 5,000 per city and about 10 per city and surname pair. A row whose `idx` is NULL holds just a table's row count, and a row whose `idx` equals `tbl` describes a `WITHOUT ROWID` table's own primary-key B-tree. Three behaviours catch people out: - Statistics are **not updated** as rows change. They describe the data at the moment ANALYZE ran. - The planner loads them when it reads the schema, so edits made directly to `sqlite_stat1` take effect only after `ANALYZE sqlite_schema` forces a reload. - Histogram samples go to `sqlite_stat4` only in builds compiled with `SQLITE_ENABLE_STAT4`, and only from a full scan. ## Keeping statistics fresh with PRAGMA optimize The documentation's recommended pattern: 1. A connection that lives briefly runs `PRAGMA optimize;` once, just before it closes. 2. A connection that stays open runs `PRAGMA optimize=0x10002;` when it opens, then `PRAGMA optimize;` periodically, perhaps daily or hourly. 3. Every application runs `PRAGMA optimize;` after a schema change, especially after `CREATE INDEX`. The argument is a bitmask. `0x00002` (on by default) allows ANALYZE on tables that might benefit, `0x00010` (on by default) caps each ANALYZE with a temporary analysis limit, and `0x10000` (off by default) checks every table instead of only those this connection used. A new connection has no query history, which is why the open-time call adds `0x10000`. `PRAGMA optimize(-1)` lists what it would do without doing it. ## When it actually runs ANALYZE In the current implementation, a table is analyzed only if it is an ordinary table and: - this connection's planner used its statistics, the `0x10000` bit is set, or one of its indexes has no `sqlite_stat1` row, and - one of its indexes still lacks a `sqlite_stat1` row, or its row count has grown or shrunk about tenfold since the last ANALYZE. Most calls therefore do nothing and return almost at once. The documentation says these rules are likely to change between releases. ## Older libraries and frozen statistics - `PRAGMA optimize` arrived in 3.18.0 and is a no-op before it. It was significantly enhanced in 3.46.0, which added its automatic limit on ANALYZE work. The SQLite inside a phone's operating system is often older than the current release, and older releases came with different advice: set `PRAGMA analysis_limit` (3.32.0 and later; default 0, meaning no limit) to a value between 100 and 1000 before analyzing. - Some teams prefer that millions of installs run exactly the plans they tested. Their recipe is to never run ANALYZE or `PRAGMA optimize` in the app, capture `sqlite_stat1` from a representative test database, insert those rows when the app creates its database, and run `ANALYZE sqlite_schema` to load them. - Running ANALYZE almost always improves plans, but the documentation admits pathological cases where a query gets slower. Frozen statistics trade that risk for plans that never adapt to a user's data.

  • In SQLite, why might a team ship a fixed sqlite_stat1 instead of letting each install run PRAGMA optimize?
    So every installed copy runs the same plans that were tested, which makes field performance reports reproducible. They run ANALYZE once on a representative test database, capture the `sqlite_stat1` rows as INSERT statements, apply them when the app creates its database, then run `ANALYZE sqlite_schema` to load them. The cost is plans that never adapt to an unusual user's data.
  • In SQLite, you inserted rows into sqlite_stat1 by hand but plans did not change; why?
    The planner loads the statistics tables into memory when it reads the schema, so it does not see direct edits right away. Running `ANALYZE sqlite_schema` makes it reread them. The documentation also warns that invalid statistics can produce poor plans, so hand edits should come only from a captured, known-good ANALYZE.
  • In SQLite, what does sqlite_stat4 add over sqlite_stat1, and when do you get it?
    `sqlite_stat4` stores sampled index entries that let the planner estimate ranges and skewed values better than averages can. It is collected only when SQLite is compiled with `SQLITE_ENABLE_STAT4`, and only by a full-scan ANALYZE: with a non-zero analysis limit it is not computed.

  • SQLite updates sqlite_stat1 automatically as rows are inserted and deleted.
  • SQLite will not use any index until ANALYZE has been run.
  • PRAGMA optimize rebuilds and defragments the indexes, like VACUUM.
  • On a new connection, plain PRAGMA optimize already checks every table.
  • sqlite_stat1 stores a histogram of each column's values.

Assumes SQLite 3.53; PRAGMA optimize arrived in 3.18.0 and since 3.46.0 limits its own ANALYZE work, which older bundled libraries do not do.