Finding slow spots in SQLite queries: reading query plans and choosing indexes

2026-11-04

A query plan shows how SQLite intends to run a statement, and reading it is the fastest way to find out why a query is slow. In our earlier article on improving database integrity in SQLite with foreign key constraints we looked at correctness. This article looks at speed: how to read a plan, and how indexes and a small change to a query improve it.

We take one realistic query on the Sakila sample database and read its plan in the plan analyzer of Database Workbench. Then we speed it up with an index and a small change to the query, and check the plan after each step.

Preparing a larger test database

Sakila holds roughly 16 000 rentals, so even an unindexed query finishes in a few milliseconds and the gain from an index is hard to see. To show the effect at a realistic size, work on a copy of the database and multiply the rental data. The following statement adds about 50 shifted copies of every rental, spread over later years, which gives roughly 800 000 rows:

WITH RECURSIVE n(i) AS (
    SELECT 1
    UNION ALL
    SELECT i + 1 FROM n WHERE i < 50
),
base AS (
    SELECT COALESCE(MAX(rental_id), 0) AS max_id FROM rental
)
INSERT INTO rental (rental_id, rental_date, inventory_id, customer_id, return_date, staff_id, last_update)
SELECT
    (SELECT max_id FROM base) + ROW_NUMBER() OVER (ORDER BY n.i, r.rental_id),
    datetime(r.rental_date, '+' || (n.i * 400) || ' days'),
    r.inventory_id,
    r.customer_id,
    r.return_date,
    r.staff_id,
    datetime('now')
FROM
    rental r
CROSS JOIN
    n;

ANALYZE;

The statement supplies rental_id itself, because in this copy it is a plain INT primary key that does not generate values. It needs SQLite 3.25 or later for ROW_NUMBER(). After this, the latest year holds roughly one shifted copy, about 2% of all rows, which is a realistic selective filter.

What SQLite returns: two simple plans

You ask SQLite for a plan by putting EXPLAIN QUERY PLAN in front of a statement. Before we look at a larger query, here are two small ones on the film table. The first looks up one film by its key:

EXPLAIN QUERY PLAN
SELECT title FROM film WHERE film_id = 42;
id  parent  notused  detail
--  ------  -------  ---------------------------------------------------
3   0       0        SEARCH film USING INDEX sqlite_autoindex_film_1 (film_id=?)

Each row of the output is one step of the plan. The detail column is the part you read. The id identifies the step, parent holds the id of the step it belongs to (0 means the top level), and notused is internal and can be ignored. The id values depend on the SQLite version, so yours may differ.

The detail line says that SQLite will search the table through an index, sqlite_autoindex_film_1, which belongs to the primary key (more on that name later). The text in brackets lists the search key: film_id=?, where the question mark stands for the value you look for. A search jumps straight to the matching rows, however large the table is.

The second query asks for the long films, sorted by title:

EXPLAIN QUERY PLAN
SELECT title FROM film WHERE length > 180 ORDER BY title;
id  parent  notused  detail
--  ------  -------  ----------------------------
3   0       0        SCAN film
11  0       0        USE TEMP B-TREE FOR ORDER BY

This plan has two steps, both at the top level. SCAN film means that SQLite reads every row of the table, because no index can help with the condition on length. The second step says that the result is sorted in a temporary structure, because no index delivers the films in title order. On a table of 1 000 films this is not a problem. On a table of 800 000 rows it would be.

Two words to remember: a SEARCH goes straight to the rows it needs through an index, and a SCAN reads everything. Most of this article is about turning scans into searches.

The example query

The query returns the ten most rented films in the most recent year that has rental data. It uses two common table expressions (CTEs): one finds the latest year, the other counts rentals per film for that year.

WITH latest_rental_year AS (  /* find the most recent year available in the database */
    SELECT strftime('%Y', MAX(rental_date)) AS latest_year 
    FROM rental
),
film_rental_counts AS (  /* count rentals per film for the most recent year found */
    SELECT
        f.film_id,
        f.title,
        COUNT(r.rental_id) AS rental_count
    FROM
        film f
    JOIN
        inventory i ON f.film_id = i.film_id
    JOIN
        rental r ON i.inventory_id = r.inventory_id
    WHERE
        strftime('%Y', r.rental_date) = (SELECT latest_year FROM latest_rental_year)
    GROUP BY
        f.film_id, f.title
)
SELECT /* return the top 10 most rented films */
    film_id,
    title,
    rental_count
FROM
    film_rental_counts
ORDER BY
    rental_count DESC
LIMIT 10;

The query is correct and easy to read, which is why it makes a good example: nothing in it looks wrong, and the plan still has something to tell us. Before changing anything, list the indexes that exist on the three tables, because the plan can only be judged against them:

SELECT tbl_name, name, sql
FROM sqlite_master
WHERE type = 'index'
  AND tbl_name IN ('film', 'inventory', 'rental')
ORDER BY tbl_name, name;

Our copy of Sakila has these indexes on the three tables:

TableIndexColumns
filmsqlite_autoindex_film_1 (primary key)film_id
filmidx_fk_language_idlanguage_id
filmidx_fk_original_language_idoriginal_language_id
inventorysqlite_autoindex_inventory_1 (primary key)inventory_id
inventoryidx_fk_film_idfilm_id
inventoryidx_fk_film_id_store_idstore_id, film_id
rentalsqlite_autoindex_rental_1 (primary key)rental_id
rentalidx_rental_uq (unique)rental_date, inventory_id, customer_id
rentalidx_rental_fk_inventory_idinventory_id
rentalidx_rental_fk_customer_idcustomer_id
rentalidx_rental_fk_staff_idstaff_id

These indexes are used by the plan of the original query: idx_rental_uq, which starts with rental_date and answers the MAX(rental_date) subquery; sqlite_autoindex_film_1, the automatic primary key index of film; idx_fk_film_id, which finds the inventory items of a film; and idx_rental_fk_inventory_id, which finds the rentals of an inventory item. None of them helps the filter on the year of rental_date. Your copy may differ slightly, so run the query above before following along.

Reading the plan in the plan analyzer

SQLite produces a plan with EXPLAIN QUERY PLAN. For our query it returns the output below. The id and parent columns show how the steps nest, and notused is internal and can be ignored.

id  parent  notused  detail
--  ------  -------  ---------------------------------------------------------------
2   0       0        CO-ROUTINE film_rental_counts
14  2       105      SCAN f USING INDEX sqlite_autoindex_film_1
17  2       52       SEARCH i USING INDEX idx_fk_film_id (film_id=?)
23  2       99       SEARCH r USING INDEX idx_rental_fk_inventory_id (inventory_id=?)
34  2       0        SCALAR SUBQUERY 2
37  34      0        CO-ROUTINE latest_rental_year
40  37      209      SEARCH rental USING COVERING INDEX idx_rental_uq
53  34      16       SCAN latest_rental_year
95  0       82       SCAN film_rental_counts
109 0       0        USE TEMP B-TREE FOR ORDER BY

The output is accurate, but you need to know SQLite's vocabulary to read it, and nothing says which lines deserve attention. The access to rental appears only as SEARCH r USING INDEX ..., using the alias from the query, and nothing in that line says whether the year condition takes part in the search.

The plan analyzer in Database Workbench shows the same plan in a form that is easier to act on.

SQLite query plan in Database Workbench

What the analyzer adds to the raw plan:

Here is how each line of our plan translates:

Raw plan linePlan analyzerWhat it means
CO-ROUTINE film_rental_countsCo-routine film_rental_countsThe CTE runs on demand and feeds rows to the outer query, instead of being stored first.
SCAN f USING INDEX sqlite_autoindex_film_1Scan index sqlite_autoindex_film_1All films are read in primary key order, plus the table row for each film to get the title.
SEARCH i USING INDEX idx_fk_film_id (film_id=?)Search index idx_fk_film_idFor each film, its inventory items are found through the foreign key index.
SEARCH r USING INDEX idx_rental_fk_inventory_id (inventory_id=?)Search index idx_rental_fk_inventory_idFor each inventory item, its rentals are found through the foreign key index. The year condition is not part of the search.
SCALAR SUBQUERY 2Scalar subquery 2The subquery in the WHERE clause, which SQLite runs once.
CO-ROUTINE latest_rental_yearCo-routine latest_rental_yearThe first CTE, run on demand inside the subquery.
SEARCH rental USING COVERING INDEX idx_rental_uqSearch covering index idx_rental_uqMAX(rental_date) is answered from the end of an index, without touching the table.
SCAN latest_rental_yearScan table latest_rental_yearReads the one-row result of the first CTE.
SCAN film_rental_countsScan table film_rental_countsThe outer query reads the CTE's output.
USE TEMP B-TREE FOR ORDER BYSort (ORDER BY)The result is sorted in a temporary structure.

Read top to bottom, the plan says this: SQLite walks through all films in primary key order, finds the inventory items of each film with idx_fk_film_id, and finds the rentals of each item with idx_rental_fk_inventory_id. Because the films arrive in film_id order, the grouping on f.film_id and f.title needs no temporary structure. Now look at the step on r. The search key is only inventory_id. The year condition is not part of it, so SQLite reads every row of rental through the index, fetches the table row to get rental_date, and evaluates the strftime condition on each. The analyzer does not flag this step, because each lookup is an index search, but the work adds up to a pass over the whole table. This is the expensive step, and it is the one the rest of this article removes.

How can you tell, when no line says SCAN rental? The text in brackets after an index search lists the search keys, and here the only key is inventory_id. The year condition is not listed, so it cannot narrow the search. SQLite finds the rentals of each inventory item through the index, reads the table row to get rental_date, and only then evaluates the condition. Every rental refers to an inventory item through a foreign key, and the plan visits every inventory item by way of the films, so every rental is reached once. The result is a full pass over rental, disguised as a series of index searches.

What is sqlite_autoindex?

Names such as sqlite_autoindex_inventory_1 belong to indexes that SQLite creates by itself. Whenever a table has a PRIMARY KEY that is not an alias for the rowid, or a UNIQUE constraint, SQLite needs an index to enforce it, and it builds one named sqlite_autoindex_<table>_<n>, where n counts the constraints of that table. They are ordinary B-tree indexes and the planner uses them like any other index, which is why the lookups on inventory and film appear in the plan as index searches. You cannot drop them, because they belong to the constraint, and they have no CREATE INDEX statement: the sql column in sqlite_master is NULL.

Do not confuse them with the automatic indexes that SQLite sometimes builds for a single query. Those are temporary, are shown in a plan as AUTOMATIC INDEX, and disappear when the query ends. Seeing one is a hint that a permanent index is missing.

Grades of warnings

The plan analyzer does not treat all steps alike. For SQLite plans it grades the steps that deserve attention as Notice (worth a look, often harmless), Warning (a likely problem) or Critical (almost always a problem). In the plan, these steps are shown in bold, with warnings in dark yellow and critical steps in red. These are the cases it detects:

GradeCaseWhat it means and what the analyzer suggests
CriticalFull scan inside a correlated subqueryThe scan is repeated for every row of the outer query. Create an index on the join or condition columns, and check for a function or expression on the column, a leading wildcard or a data type mismatch, because these prevent index use.
CriticalFull scan on the inner side of a joinA scan in a loop that comes after another loop of the same parent. The advice is the same as above.
WarningAutomatic indexSQLite builds a temporary index on every execution, because no permanent index is available. Create a permanent index on the search columns.
NoticeFull table scan (not repeated)Not reported for a scan of derived data: the result of a co-routine, a materialized subquery or a CTE, as those cannot be indexed. Add a condition on an indexed column, or create an index on the WHERE/join column(s).
NoticeFull index scan (not repeated)The whole index is read, plus the table row for each entry. A scan of a covering index or of a virtual table gets no notice. Add a condition on the leading columns of the index, or make the index cover the query.
NoticeTemporary B-tree for ORDER BY, GROUP BY or DISTINCTCreate an index on the ORDER BY, GROUP BY or DISTINCT columns.
NoticeOther temporary B-treeNo suggestion.
NoticeCorrelated subqueryThe subquery is evaluated again for every row of the outer query. Rewrite it as a join, and make sure the columns used from the outer query are indexed.
NoticeSearch without a named index (typically MIN() or MAX())This is a single seek if an index or the rowid gives the order, and a full scan otherwise. The plan text does not say which, so make sure the column is indexed.

A full scan that is not repeated, such as our scan of the index on film, is a notice. The same scan inside a correlated subquery or on the inner side of a join would be critical, because the cost multiplies with every repetition.

In our plan, the flagged steps carry the info icon, which means they are notices: the scan of the index on film, the scans of the two CTEs and the sort. The step that matters most, the search on rental, is not flagged at all, because every lookup is an index search. A notice is a prompt, not a verdict, and an unflagged step can still be the expensive one. Only reading the plan reveals it: here, the year condition is missing from the search key.

Step 1: make the date filter usable by an index

The condition strftime('%Y', r.rental_date) = ... applies a function to the column. An index on rental_date is sorted by the stored value, not by the year computed from it, so SQLite cannot use the index to jump to the matching rows. It has to read every row and compute the year each time. A condition that an index can use is called sargable (Search ARGument ABLE).

The fix is an index on the expression itself, so the query can stay exactly as it is. In our tests, this turned out to be the most useful index for the original query.

SQLite can index an expression, and the optimizer uses such an index when the query contains exactly the same expression:

CREATE INDEX idx_rental_year
    ON rental (strftime('%Y', rental_date), inventory_id);

Run the original query again and look at the plan:

id  parent  notused  detail
--  ------  -------  ---------------------------------------------------------------
2   0       0        CO-ROUTINE film_rental_counts
14  2       62       SEARCH r USING INDEX idx_rental_year (<expr>=?)
17  2       0        SCALAR SUBQUERY 2
20  17      0        CO-ROUTINE latest_rental_year
23  20      209      SEARCH rental USING COVERING INDEX idx_rental_uq
36  17      16       SCAN latest_rental_year
47  2       41       SEARCH i USING INDEX sqlite_autoindex_inventory_1 (inventory_id=?)
53  2       38       SEARCH f USING INDEX sqlite_autoindex_film_1 (film_id=?)
59  2       0        USE TEMP B-TREE FOR GROUP BY
101 0       82       SCAN film_rental_counts
115 0       0        USE TEMP B-TREE FOR ORDER BY
New SQLite query plan in Database Workbench

The pass over every row of rental is gone. In its place, SQLite does a search on idx_rental_year for the table r, with the computed year as the search key (the plan analyzer shows it as <expr>). The primary key lookups on inventory and film now follow that search, one per matching rental. The grouping needs a temporary structure again, because the rows now arrive in the order of rental instead of in film order. What remains are the scans of the two CTEs, which are cheap, and the group and sort steps that we deal with in step 3.

Some points to keep in mind:

It also helps to know how selective the filter is. This query shows how many rows the latest year holds compared with the whole table:

SELECT strftime('%Y', rental_date) AS rental_year, COUNT(*) AS rentals
FROM rental
GROUP BY rental_year
ORDER BY rental_year;

In the standard Sakila data we would expect almost all rentals in 2005 and only a few hundred in early 2006. On the enlarged test database described at the start of this article, the rentals are spread over many years, and the latest year holds roughly 2% of the table. That is a selective filter, which is the ideal case for an index. A filter that matches half the table gains little from one.

Step 2: group on the narrow column, join the title afterwards

After step 1, finding the rentals is fast, but the counting step still carries more than it needs. The CTE film_rental_counts joins film for every rental row, only to group on f.film_id and f.title. The title does not belong in the counting step. We can count rentals per film_id, which inventory already holds, and fetch the title in the outer query with a join on film using the film_id from the CTE:

WITH latest_rental_year AS (
    SELECT strftime('%Y', MAX(rental_date)) AS latest_year
    FROM rental
),
film_rental_counts AS (
    SELECT
        i.film_id,
        COUNT(r.rental_id) AS rental_count
    FROM
        inventory i
    JOIN
        rental r ON i.inventory_id = r.inventory_id
    WHERE
        strftime('%Y', r.rental_date) = (SELECT latest_year FROM latest_rental_year)
    GROUP BY
        i.film_id
)
SELECT
    frc.film_id,
    f.title,
    frc.rental_count
FROM
    film_rental_counts frc
JOIN
    film f ON f.film_id = frc.film_id
ORDER BY
    frc.rental_count DESC
LIMIT 10;

What changes:

Open the plan again:

id  parent  notused  detail
--  ------  -------  ---------------------------------------------------------------
2   0       0        CO-ROUTINE film_rental_counts
11  2       62       SEARCH r USING INDEX idx_rental_year (<expr>=?)
14  2       0        SCALAR SUBQUERY 2
17  14      0        CO-ROUTINE latest_rental_year
20  17      209      SEARCH rental USING COVERING INDEX idx_rental_uq
33  14      16       SCAN latest_rental_year
44  2       41       SEARCH i USING INDEX sqlite_autoindex_inventory_1 (inventory_id=?)
50  2       0        USE TEMP B-TREE FOR GROUP BY
91  0       82       SCAN frc
94  0       38       SEARCH f USING INDEX sqlite_autoindex_film_1 (film_id=?)
112 0       0        USE TEMP B-TREE FOR ORDER BY
SQLite query plan for the improved query in Database Workbench

It shows what we hoped for. Inside the CTE, SQLite searches idx_rental_year for r, looks up inventory by primary key and groups the rows. The lookup on film (f) now comes after the scan of the CTE, which the plan shows under its alias frc, and it happens once per film instead of once per rental. The group and sort steps remain, and step 3 looks at them.

Step 3: read the GROUP BY and ORDER BY warnings

The plan analyzer flags two temporary structures: one for GROUP BY and one for ORDER BY. They deserve different treatment.

The sort cannot be avoided. We sort by rental_count, which is an aggregate computed during the query. No index can contain it, so SQLite must sort the grouped rows. With LIMIT 10 it only needs to keep the best ten, so this step is cheap. Leave it alone.

The grouping is not worth an index. The analyzer suggests an index on the GROUP BY columns. Here that advice does not help: the grouping column i.film_id comes from inventory, but the rows arrive in the order of the index on rental, so no index on inventory can deliver them sorted. The temporary structure holds one entry per film that was rented in the year, so at most 1,000 entries in Sakila. That is small compared with the scan we removed in step 1.

A warning in a plan is a prompt to think, not an instruction to follow. Decide whether the step is expensive for your data before you add an index for it. In this query the expensive step was the pass over every row of rental, and the index from step 1 removed it.

Measuring the difference

A plan tells you what SQLite will do, and a timing tells you whether it matters. Measure both, and change one thing at a time.

SQLite chooses between indexes based on statistics. After creating idx_rental_year, or after loading a lot of data, run ANALYZE; (or the lighter PRAGMA optimize;) so the planner works with accurate numbers, then open the plan again.

Run each variant the same way on the larger copy:

  1. Open the plan for the query and note the operations.
  2. Run the query once and discard the time, because the first run fills the cache.
  3. Run it five times and note the median.
  4. Compare the result with the original query.

Record the figures in a table like this one:

VariantPlan highlightsMedian time (ms)
Original query, without idx_rental_yearSearch index idx_rental_fk_inventory_id, every row of rental visited~ 7000
Step 1: expression index on strftime('%Y', rental_date), inventory_idSearch index idx_rental_year~ 40
Step 2: title joined in the outer query, index from step 1Search index idx_rental_year, group on film_id, one film lookup per group~ 15

The first row is the baseline, so measure it before you create the index, or drop idx_rental_year on the test copy. The third row runs the modified query from step 2 with the index from step 1 in place. Compare the counts with those of the original query. Films with equal counts may come in a different order.

Rules of thumb

An index on the filter expression stopped SQLite from reading every row of rental, and a leaner grouping moved the title lookup out of the counting step. The habits behind these changes apply to most queries:

  1. Look at the plan before you change anything, and again after every change. A plan that did not change means the change did not help.
  2. Start with the highest-graded steps, and hunt for scans. The plan analyzer shows the steps that deserve attention in bold: notices as they are, warnings in dark yellow and critical steps in red. A scan of a small table is fine, and a scan that is not repeated is only a notice. A scan of a large table that feeds a selective filter is the thing to fix. A scan that is repeated, as in a correlated subquery or on the inner side of a join, is critical.
  3. Do not wrap filtered columns in functions. If you cannot change the query, create an expression index that matches it exactly.
  4. Put the filtered column first in a composite index, followed by the columns used for joining. Adding more columns to make the index cover the query only pays off if the plan shows that it does.
  5. Index foreign key columns that are joined or checked often. SQLite does not do it for you, and deleting parent rows with foreign keys enabled is where a missing index hurts most.
  6. Treat suggestions as prompts. The analyzer points at the step, and you decide with knowledge of your data whether an index pays for its cost on writes.
  7. Keep statistics current. Run ANALYZE or PRAGMA optimize after large changes so the planner chooses with accurate numbers.

The plan analyzer in Database Workbench supports this routine. It names the operations in plain terms, separates operation from object and grades the steps that deserve attention as notice, warning or critical. For each of them it explains what happens and suggests what to try, such as an index on the filtered column. Open the plan, start with the highest-graded step, and ask whether an index or a different query shape can remove it.

Latest Articles