Skip to content
KALANBLON
Show contents

Chapter 4 of 7 · 20 min

Indexes and query plans

By the end of this chapter, you'll be able to

  • Read a query plan with EXPLAIN QUERY PLAN
  • Create an index and check that it is used
  • Choose the column order of a composite index
  • Recognise a condition that prevents an index from being used

Reading a query plan

The example database contains 20,000 customers and 60,000 orders, generated by a recursive CTE. EXPLAIN QUERY PLAN in front of a query doesn't run it: it shows the chosen strategy. The column we care about is detail (the other three are internal numbers):

EXPLAIN QUERY PLAN
SELECT * FROM customers WHERE email = 'customer42@example.org';
id | parent | notused | detail
2 | 0 | 216 | SCAN customers

SCAN customers: SQLite is going to read all 20,000 rows one by one to find a single email. That's a full scan.

Creating an index

An index is a sorted structure, stored separately, that maps each value of a column to the rows that contain it, like the index at the back of a book. SQLite uses a B-tree: finding one value among a million takes about twenty comparisons instead of a million.

CREATE INDEX idx_customers_email ON customers(email);
EXPLAIN QUERY PLAN
SELECT * FROM customers WHERE email = 'customer42@example.org';
SELECT id, country FROM customers WHERE email = 'customer42@example.org';
id | parent | notused | detail
3 | 0 | 62 | SEARCH customers USING INDEX idx_customers_email (email=?)
id | country
42 | VN

SEARCH … USING INDEX: the database goes straight to the relevant rows. The INTEGER PRIMARY KEY is already an index: looking up by id is always fast.

The index gives the row's location: a single row is read from the table.

Step 4 of 4
Text description of the animation
  1. We're looking for a customer by email.
  2. Without an index, SQLite compares the email of every one of the 20,000 rows: the cost grows with the table.
  3. With the sorted index, the search goes down the B-tree, the way you look up a word in a dictionary.
  4. The index gives the row's location: a single row is read from the table.

An index has a cost: it takes up space, and every INSERT, UPDATE or DELETE must update it too. So you index the columns often used in WHERE clauses, joins and ORDER BY, not every column.

Composite indexes

An index can cover several columns. The order matters: the index (customer_id, date) is sorted by customer, then by date within a customer, like a phone book sorted by surname then first name.

CREATE INDEX idx_orders_customer_date ON orders(customer_id, date);
EXPLAIN QUERY PLAN
SELECT date, amount FROM orders WHERE customer_id = 42 AND date >= '2026-01-01';
EXPLAIN QUERY PLAN
SELECT customer_id, amount FROM orders WHERE date >= '2026-09-01';
id | parent | notused | detail
3 | 0 | 51 | SEARCH orders USING INDEX idx_orders_customer_date (customer_id=? AND date>?)
id | parent | notused | detail
2 | 0 | 216 | SCAN orders
  • The first query filters on customer_id then on date: the index is fully used.
  • The second filters only on date: the index is useless, just as a phone book sorted by surname can't find everyone called "Ana". Rule: a composite index is usable for its columns from left to right, with no gap.

When every column a query needs is in the index, SQLite doesn't even need to read the table: it's a covering index (COVERING INDEX):

CREATE INDEX idx_orders_customer_amount ON orders(customer_id, amount);
EXPLAIN QUERY PLAN
SELECT customer_id, SUM(amount) FROM orders WHERE customer_id BETWEEN 100 AND 200 GROUP BY customer_id;
id | parent | notused | detail
6 | 0 | 151 | SEARCH orders USING COVERING INDEX idx_orders_customer_amount (customer_id>? AND customer_id<?)

Joins

A join's plan shows the order in which the tables are read. Here, with no index on the date, SQLite scans all the orders; with an index, it reads only those of the period:

EXPLAIN QUERY PLAN
SELECT c.country, COUNT(*) FROM orders AS o JOIN customers AS c ON c.id = o.customer_id WHERE o.date >= '2026-09-01' GROUP BY c.country;
CREATE INDEX idx_orders_date ON orders(date);
EXPLAIN QUERY PLAN
SELECT c.country, COUNT(*) FROM orders AS o JOIN customers AS c ON c.id = o.customer_id WHERE o.date >= '2026-09-01' GROUP BY c.country;
SELECT c.country, COUNT(*) AS orders FROM orders AS o JOIN customers AS c ON c.id = o.customer_id WHERE o.date >= '2026-09-01' GROUP BY c.country ORDER BY c.country;
id | parent | notused | detail
7 | 0 | 216 | SCAN o
11 | 0 | 45 | SEARCH c USING INTEGER PRIMARY KEY (rowid=?)
14 | 0 | 0 | USE TEMP B-TREE FOR GROUP BY
id | parent | notused | detail
8 | 0 | 205 | SEARCH o USING INDEX idx_orders_date (date>?)
12 | 0 | 45 | SEARCH c USING INTEGER PRIMARY KEY (rowid=?)
15 | 0 | 0 | USE TEMP B-TREE FOR GROUP BY
country | orders
BR | 558
CA | 558
MA | 651
SN | 558
VN | 651

USE TEMP B-TREE FOR GROUP BY indicates a temporary sort for the grouping: acceptable on a small result. On c, INTEGER PRIMARY KEY (rowid=?): the join benefits from the primary key.

Your turn

Mini-lab: speeding up a querySQLite

Result

Click “Run”: the SQL engine (about 1 MB) will load in your browser the first time.

A fresh SQLite database is created on every run, in your browser · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Worked exercise

Solved exercise: a customer's history

The "My orders" page shows a customer's orders, from most recent to oldest. Create the most suitable index for the query SELECT date, amount FROM orders WHERE customer_id = 42 ORDER BY date DESC, and check with the plan that there's neither a full scan nor a temporary sort.

Hint 1
The filter is on customer_id, the sort on date: a composite index in that order serves both.
Hint 2
Add amount as the last column: the index becomes covering, and SQLite no longer reads the table at all.
Show the solution and common mistakes
CREATE INDEX idx_orders_history ON orders(customer_id, date, amount);
EXPLAIN QUERY PLAN
SELECT date, amount FROM orders WHERE customer_id = 42 ORDER BY date DESC;
id | parent | notused | detail
3 | 0 | 56 | SEARCH orders USING COVERING INDEX idx_orders_history (customer_id=?)

No SCAN, no USE TEMP B-TREE FOR ORDER BY: the index delivers customer 42's rows already sorted by date (SQLite simply walks it backwards for DESC), and holds every column displayed.

Common mistakes:

  • Creating two separate indexes, one on customer_id and one on date: SQLite uses only one per table in this query, and must sort afterwards.
  • Reversing the order (date, customer_id): the filter on the customer can no longer use the index efficiently.

Summary

  1. 1EXPLAIN QUERY PLAN shows the strategy: SCAN reads the whole table, SEARCH uses an index.
  2. 2An index speeds up reads but slows down writes: index the columns of frequent WHERE clauses, joins and sorts.
  3. 3A composite index is used from left to right; it becomes covering if it holds every useful column.
  4. 4A function applied to a column prevents its index from being used, unless there's an index on the expression.
  5. 5Measure with the plan before and after: an index that doesn't show up in the plan is useless.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.