SQLite · Databases

SQLite Indexes Explained: How to Find and Fix Slow Queries

Start with one slow query, read what SQLite says about it, and fix it one index at a time.

Pink and teal risograph print of index cards with tabs, next to the words A to Z.

The “my orders” page was fast for months. Then the shop grew. The table went from a few thousand orders to a couple of hundred thousand, and the same page started to feel slow. Nobody touched the query. The data just got bigger.

Most of the time the fix is one CREATE INDEX. The hard part is knowing which one, and knowing that it worked. SQLite will tell you, if you ask. This post takes one slow query, asks SQLite how it runs it, and fixes it in four steps. Every plan below is real output from SQLite 3.51 on 200,000 generated orders.

Short version:

  • EXPLAIN QUERY PLAN shows how SQLite runs a query. SCAN means it reads every row. SEARCH ... USING INDEX means it jumps straight to the rows.
  • For a composite index, put the = columns first, then one range column, then the ORDER BY column. Add the columns you select at the end to skip the table.
  • An index is not free. It slows every write, and one on a column with few distinct values often does nothing. Run PRAGMA optimize so SQLite knows your data.

The slow query

Here is the table. The orders table has one row per order, and the page asks for the 20 newest paid orders of one customer.

CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  customer_id INTEGER NOT NULL,
  status      TEXT    NOT NULL,   -- 'pending', 'paid' or 'refunded'
  total_cents INTEGER NOT NULL,
  created_at  TEXT    NOT NULL,   -- '2025-01-14 09:30:00'
  note        TEXT
);

To follow along, fill it with random data. The numbers will differ from mine, but the plans will match.

WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 200000)
INSERT INTO orders (customer_id, status, total_cents, created_at, note)
SELECT 1 + abs(random()) % 1000,
       CASE WHEN abs(random()) % 100 < 2  THEN 'pending'
            WHEN abs(random()) % 100 < 10 THEN 'refunded'
            ELSE 'paid' END,
       abs(random()) % 50000,
       datetime('2025-01-01', '+' || (i % 500) || ' hours'),
       'note for order ' || i
FROM n;

The slow query, with EXPLAIN QUERY PLAN in front:

EXPLAIN QUERY PLAN
SELECT id, total_cents, created_at
FROM orders
WHERE customer_id = 42 AND status = 'paid'
ORDER BY created_at DESC
LIMIT 20;
QUERY PLAN
|--SCAN orders
`--USE TEMP B-TREE FOR ORDER BY

Two lines, two problems. SCAN orders means SQLite reads all 200,000 rows to find the few that belong to customer 42. USE TEMP B-TREE FOR ORDER BY means it then sorts what it found, because nothing hands the rows over in order.

In the SQLite shell, .eqp on prints the plan before every query result, which saves typing. The SQLite docs say the plan text is for people, and its format can change between releases, so do not parse it in your code.

What an index is

An index is a sorted copy of some columns, plus the rowid of each row. The rowid is the number SQLite uses to find the row in the table. The query planner docs describe it as another table with the indexed content stored in front of the rowid and all rows in content order.

Two strips of customer ids. Without an index SQLite reads every row to find customer 42. With an index the ids are sorted, so SQLite jumps to the first 42, reads the three matches and stops.

Because the copy is sorted, SQLite can use a binary search: look at the middle, decide which half to keep, repeat. The cost grows with the logarithm of the row count, not with the row count. The table itself is also a sorted tree, keyed by rowid, so once the index gives a rowid, a second search finds the row.

How an index finds a row: SQLite compares 42 with the root page keys, follows a branch to a leaf, finds rowid 8812 for customer 42, then reads that row from the orders table.

The file format docs call this a B-tree. Each index entry is the indexed column values followed by the rowid. You never build it by hand. CREATE INDEX does it, and SQLite keeps it in step with the table on every write.

Reading EXPLAIN QUERY PLAN

Five phrases cover almost every plan you will see.

How to read EXPLAIN QUERY PLAN: SCAN reads every row, SEARCH USING INDEX jumps to matches, COVERING INDEX avoids the table, and USE TEMP B-TREE FOR ORDER BY means an extra sort.
  • SCAN reads every row, or every entry of an index. SEARCH reads only a subset. This is the first word to look at.
  • USING INDEX name means SQLite finds rows through the index, then reads the table for the other columns.
  • USING COVERING INDEX name means the index has every column the query needs, so the table is never read.
  • (customer_id=? AND status=?) lists the conditions that the index handles. If a column you expected is missing here, it is not helping.
  • USE TEMP B-TREE FOR ORDER BY means a separate sort step. The same phrase appears for GROUP BY and DISTINCT.

A trap: SCAN orders USING COVERING INDEX idx_x is still a full scan. SQLite reads every entry in the index. It is cheaper than reading the table, because the index is smaller, but the work still grows with the table.

Fix 1: index the column in WHERE

The query filters on customer_id, so index that:

CREATE INDEX idx_orders_customer ON orders (customer_id);
QUERY PLAN
|--SEARCH orders USING INDEX idx_orders_customer (customer_id=?)
`--USE TEMP B-TREE FOR ORDER BY

SCAN became SEARCH. SQLite now finds the roughly 200 orders of customer 42 without touching the other 199,800. Two things are still wrong. It reads all 200 table rows to test status, and it still sorts them. A customer with 10,000 orders would pay for 10,000 rows and a sort on every page view.

Fix 2: one composite index

A composite index has more than one column. SQLite sorts it by the first column, uses the second to break ties, and so on. The docs give the rules for using it: the first columns must be tested with =, IN or IS, the last column used may have range tests (>, <, BETWEEN), and there can be no gaps.

That gives a recipe for column order:

  1. Equality columns first. Here customer_id and status.
  2. One range column next, if the query has one.
  3. The ORDER BY column last. Rows with the same customer_id and status are already stored in created_at order, so no sort is needed.
Composite index on customer_id, status, created_at: a query for customer 42 and status paid hits one block already sorted by created_at, so no sort. Order: equality columns, one range column, then ORDER BY.

Replace the single-column index with a composite one:

DROP INDEX idx_orders_customer;
CREATE INDEX idx_orders_customer_status_created
  ON orders (customer_id, status, created_at);
QUERY PLAN
`--SEARCH orders USING INDEX idx_orders_customer_status_created (customer_id=? AND status=?)

The temp B-tree line is gone. SQLite walks the matching block of the index from the end (that is what DESC asks for) and stops after 20 rows. We dropped the old index because it is a prefix of the new one. The planner docs give the rule: never keep two indexes where one is a prefix of the other, and drop the shorter one.

The left-most prefix rule

The composite index serves every query that starts with its first columns, and stops helping where the chain breaks. These are real plans for the index above:

Query filters onPlan
customer_idSEARCH ... (customer_id=?)
customer_id and statusSEARCH ... (customer_id=? AND status=?)
customer_id and created_at >= ?SEARCH ... (customer_id=?), the gap at status stops it
status onlycannot SEARCH, falls back to a SCAN

The third row is the one that bites. created_at is in the index, but because status is skipped, it cannot narrow the search. SQLite finds the customer’s rows and filters the dates one by one.

The same rule explains why column order matters for a range. Take a query with customer_id = ? and created_at >= ?:

IndexWhat narrows the search
(created_at, customer_id)(created_at>?), only the range
(customer_id, created_at)(customer_id=? AND created_at>?), both

Put the range column after the equality columns. A range column ends the chain, so anything to its right cannot help narrow the search.

Two more gotchas, both from real plans:

  • IN on an earlier column brings the sort back. With status IN ('paid', 'refunded') ORDER BY created_at, SQLite searches two blocks. Each block is in created_at order, but the two together are not, so you see USE TEMP B-TREE FOR ORDER BY again.
  • A range on a middle column breaks the order too. With status > 'a' ORDER BY created_at, the rows are no longer in created_at order. You cannot get both a range and an ORDER BY on different columns from one index. Pick the one that removes more rows and measure.

One composite index is also better than two single-column ones. SQLite does not intersect two indexes for an AND. The planner docs say plainly that it does not implement that technique. (For OR it can use one index per branch.)

Fix 3: a covering index

Look at the plan again. It says USING INDEX, not USING COVERING INDEX. The query selects total_cents, which is not in the index, so for each of the 20 rows SQLite goes back to the table. Add total_cents at the end:

DROP INDEX idx_orders_customer_status_created;
CREATE INDEX idx_orders_customer_status_created_total
  ON orders (customer_id, status, created_at, total_cents);
QUERY PLAN
`--SEARCH orders USING COVERING INDEX idx_orders_customer_status_created_total (customer_id=? AND status=?)
Two plans: USING INDEX finds the rowid, then reads the table row for total_cents (two lookups). USING COVERING INDEX holds total_cents already, so the table is never read (one lookup).

id is free, because it is the rowid and every index entry holds the rowid. The docs say a covering index can make many queries run about twice as fast. That is a constant factor, not a change in how the cost grows. A covering index has a price: it is a bigger index, so it uses more disk and slows writes a bit more.

It only works if the query selects columns that are all in the index. Change the query to SELECT * on this table and the plan goes back to SEARCH ... USING INDEX, because note is not in the index. Select only the columns you need. That is better for covering indexes and for everything else.

Partial indexes: index only the rows you ask for

A partial index has a WHERE clause and holds entries only for the rows where it is true. Say a back-office job looks for orders still pending. In my data that is about 2% of the table.

CREATE INDEX idx_orders_pending_customer
  ON orders (customer_id) WHERE status = 'pending';

The index is small, so it is cheap to keep and quick to search. It is used only when SQLite can prove that the query’s WHERE implies the index’s WHERE. Here are the plans for the same index:

QueryPlan
WHERE customer_id = 42 AND status = 'pending'SEARCH orders USING COVERING INDEX idx_orders_pending_customer (customer_id=?)
WHERE customer_id = 42 AND status = 'paid'SCAN orders
WHERE customer_id = 42SCAN orders
WHERE customer_id = 42 AND status = ?1SCAN orders

The last row is the surprise. A bound parameter is fine in a query, but SQLite does not know at planning time that ?1 will be 'pending', so it cannot use the index. Write the literal in the query text.

The partial index docs explain that SQLite has no general theorem prover. It uses two simple rules. First, a term in the query’s WHERE has to match a term in the index’s WHERE exactly: b=6 matches b=6, but not b=3+3 or b BETWEEN 6 AND 6. Second, if the index says z IS NOT NULL, a query that compares z with an operator other than IS (=, <, >, <>, IN, LIKE) matches. When you are unsure, run EXPLAIN QUERY PLAN.

The WHERE of the index itself cannot use subqueries, other tables, non-deterministic functions or bound parameters. A partial index can also be UNIQUE, which gives you “only one per group” rules, for example one default address per user. Partial indexes need SQLite 3.8.0 (2013) or newer, and a database that has one cannot be opened by older versions.

Indexes on expressions

Users type their email in any case, so the login query looks like this:

SELECT id FROM users WHERE lower(email) = '[email protected]';

A plain index on email does not help. The index is sorted by email, not by lower(email), so SQLite reads the whole index:

QUERY PLAN
`--SCAN users USING COVERING INDEX idx_users_email

Index the expression itself:

CREATE INDEX idx_users_email_lower ON users (lower(email));
QUERY PLAN
`--SEARCH users USING COVERING INDEX idx_users_email_lower (<expr>=?)

The query has to use the same expression. The expression index docs say the planner “does not do algebra”: an index on x+y is not used for y+x=22. In my test, lower(trim(email)) also falls back to a scan.

Expression indexes only accept deterministic functions (same input, same output), so random() is out. They need SQLite 3.9.0 (2015) or newer.

Often you can fix the query instead. Take WHERE date(created_at) = '2025-01-10'. With an index on created_at (CREATE INDEX idx_orders_created ON orders (created_at)), it is a scan, because the column is wrapped in a function. Written as a range, it uses the index:

WHERE created_at >= '2025-01-10' AND created_at < '2025-01-11'
QUERY PLAN
`--SEARCH orders USING COVERING INDEX idx_orders_created (created_at>? AND created_at<?)

LIKE and upper and lower case

LIKE can use an index, but only if the pattern does not start with a wildcard and the index uses the right collation (the rule for comparing text). By default LIKE ignores case for plain English letters. The optimizer docs say that with the default setting, the column must be indexed with COLLATE NOCASE. If you turn on PRAGMA case_sensitive_like, it must be the default BINARY collation instead.

My users.email has an ordinary index, which is BINARY. So this scans:

SELECT id FROM users WHERE email LIKE 'user42%';
QUERY PLAN
`--SCAN users USING COVERING INDEX idx_users_email

Add a NOCASE index and the same query searches a range:

CREATE INDEX idx_users_email_nocase ON users (email COLLATE NOCASE);
QUERY PLAN
`--SEARCH users USING COVERING INDEX idx_users_email_nocase (email>? AND email<?)

SQLite turns LIKE 'user42%' into a range test between user42 and the next string up. email LIKE '%example.com', with a wildcard at the start, cannot do that and scans. Equality works too: email = ? COLLATE NOCASE uses the NOCASE index.

ANALYZE and PRAGMA optimize

SQLite has to guess how many rows each index will return. ANALYZE counts and stores the answer in a table called sqlite_stat1. The ANALYZE docs describe it. The planner docs say that without it, the choice between indexes is arbitrary.

ANALYZE;
SELECT * FROM sqlite_stat1;

With one index on customer_id and one on status, the table holds this:

orders|idx_customer|200000 200
orders|idx_status|200000 66667

Read the stat column as: the index has about 200,000 entries, and each customer_id matches about 200 of them. It is an average, a single number per column. That is also why it cannot tell a common value from a rare one.

You should not have to remember to run ANALYZE. The docs recommend PRAGMA optimize, which runs it only when it is likely to help, and quickly:

-- short-lived connection: run once, just before closing
PRAGMA optimize;

-- long-lived connection: run when it opens, then now and then
PRAGMA optimize = 0x10002;
PRAGMA optimize;   -- for example once a day

-- after any schema change, especially CREATE INDEX
PRAGMA optimize;

PRAGMA optimize(-1) shows what it would do without doing it. Since SQLite 3.46.0 you do not need to set analysis_limit yourself, because optimize does it.

Statistics also switch on one more trick. With an index on (status, created_at) and a query that only filters on created_at, SQLite may use a skip-scan, which tries each value of the first column. It only does that when it knows the first column has many repeats, and it only knows after ANALYZE. In my test the plan changed from SCAN orders USING COVERING INDEX idx_status_created to SEARCH ... (ANY(status) AND created_at>?) after running ANALYZE.

When an index hurts

Every index is a second copy of your data, and SQLite keeps it in step.

  • Writes get slower. Each INSERT and DELETE changes every index, and an UPDATE does too when it changes an indexed column. As a rough check, I inserted 200,000 rows in one transaction on my laptop: about 0.11 seconds with no extra indexes, about 0.47 seconds with four. Your numbers will differ, but the direction will not.
  • Indexes on columns with few distinct values rarely help. An index on status has three values. For status = 'paid', which is 90% of my table, SQLite still picked the index, and the query was no faster than a scan in my test. The stat row above shows why: it knows 66,667 rows per value on average, not that paid is most of them.
  • Redundant indexes waste space and slow writes. If you have (customer_id) and (customer_id, status), the first is not needed.
  • An index nobody uses still costs. To check, run EXPLAIN QUERY PLAN on your real queries. If no plan names an index, it is a candidate to drop.
  • Building one takes the write lock. CREATE INDEX on a big table is a write for as long as it takes. Do it when it is quiet. A related point from how SQLite locks work: a query that needs less time also holds its locks for less time, so a good index helps writers too.

For settings that matter in production, such as WAL mode and busy timeouts, see SQLite for high-traffic websites. If you also run PostgreSQL, the lock side of the same story is in Understanding PostgreSQL locks.

Which index should I add?

Which index to add: leave alone unless the plan shows SCAN or a TEMP B-TREE sort on a hot query. Then use an expression, partial, covering or composite index, and read the plan again.

And as a table, for the common query shapes:

Query shapeIndex
WHERE a = ?(a)
WHERE a = ? AND b = ?(a, b)
WHERE a = ? AND c > ?(a, c)
WHERE a = ? ORDER BY c(a, c)
WHERE a = ? AND b = ? ORDER BY c(a, b, c)
the same, selecting d too(a, b, c, d)
WHERE lower(a) = ?(lower(a))
WHERE status = 'pending' on a big table(a) WHERE status = 'pending'

Questions people ask

How do I know if SQLite is using my index? Put EXPLAIN QUERY PLAN in front of the query and look for the index name. SEARCH ... USING INDEX name or USING COVERING INDEX name means yes. SCAN with no index means no. In the SQLite shell, .eqp on does this for every query.

Why does SQLite ignore my index? The usual causes: the column is wrapped in a function (lower(email)), a LIKE pattern starts with %, the LIKE collation does not match the index, a column earlier in the composite index is missing from the WHERE, or a partial index’s WHERE is not implied by the query. Without ANALYZE the planner is also guessing, so run PRAGMA optimize.

Does column order in a composite index matter? Yes. Equality columns first, then one range column, then the ORDER BY column. The index can only be used from its left-most column, with no gaps. (a, b) serves WHERE a = ?, but not WHERE b = ?.

Do I need to index the primary key? Not an INTEGER PRIMARY KEY. That column is the rowid, and a lookup shows SEARCH orders USING INTEGER PRIMARY KEY (rowid=?). Other PRIMARY KEY and UNIQUE constraints get an index created for them automatically.

Can SQLite use two indexes for one table? Usually one per table in a query. The main exception is OR, where each side can use its own index. It does not intersect two indexes for AND, so build one composite index instead.

Cheat sheet

SQLite index cheat sheet: read EXPLAIN QUERY PLAN, want SEARCH not SCAN. Put equality columns first, one range column, then ORDER BY. Cover hot queries, run PRAGMA optimize, and change one thing at a time.

Further reading

Written by Rafi Loom

Backend engineer who builds high-volume systems that move money. More about Rafi