25. Indexes: finding rows fast

Like the index at the back of a book: what an index is, when it helps, what it costs, and how to keep it working.

What an index is

To find every page about "rice" in a thick cookbook, you can read it from the first page to the last, or you can turn to the index at the back: the words in order, each with its page numbers. A few seconds instead of an afternoon.

A database does the same. Without help, WHERE customer_id = 1 has to read every row of orders and test each one (a scan). With 15 orders nobody notices; with 15 million, the program waits. An index is a list the database keeps beside the table: one column's values in order, each with the row it came from. In an ordered list the database can jump straight to the values it wants (a search), the way you find a word in a dictionary without reading it all.

Two things to keep in mind from the start:

CREATE INDEX

Looking up a customer's orders is something the shop does all day. Give orders.customer_id an index:

CREATE INDEX idx_orders_customer ON orders (customer_id);
SELECT id, ordered, status FROM orders WHERE customer_id = 1;
idorderedstatus
12026-09-02paid
32026-09-12shipped
102026-10-28paid
3 rows

The name is yours to choose; a common habit is idx_ + table + columns, so the name says what it is. The query is written exactly as before: you never name an index in a SELECT, the database chooses one by itself.

You can't see the difference in the result, by design. To see which way the database finds the rows, SQLite has EXPLAIN QUERY PLAN. Phai SQL doesn't have that statement; in Phai Database Studio, Display Plan shows a query's plan. Here is what SQLite says for this query, before and after the index:

-- before CREATE INDEX: read every row
SCAN orders
-- after: jump to customer_id = 1 in the index
SEARCH orders USING INDEX idx_orders_customer (customer_id=?)

SCAN reads the whole table; SEARCH ... USING INDEX goes straight to the rows. On a big table that is the difference between seconds and milliseconds.

Seeing the indexes: PRAGMA index_list and index_info

PRAGMA index_list(table) lists a table's indexes:

PRAGMA index_list(orders);
seqnameuniqueoriginpartial
0idx_orders_customer0c0
1 row

unique is 1 for an index that allows no repeats, origin says where it came from (c: CREATE INDEX; u: a UNIQUE in the table; pk: a PRIMARY KEY that isn't the INTEGER PRIMARY KEY), and partial is 1 for an index with a WHERE. Some indexes the database makes by itself. order_item's key is two columns, so it gets one:

PRAGMA index_list(order_item);
seqnameuniqueoriginpartial
0sqlite_autoindex_order_item_11pk0
1 row

PRAGMA index_info(index) says which columns an index holds, in order:

PRAGMA index_info(sqlite_autoindex_order_item_1);
seqnocidname
00order_id
11product_id
2 rows

UNIQUE INDEX

A UNIQUE INDEX is an index that also makes a rule: no two rows may have the same value. Two customers should never share a phone number:

CREATE UNIQUE INDEX idx_customer_phone ON customer (phone);
✓ Done

Now a second customer with Somchai's number is refused:

INSERT INTO customer (id, name, phone) VALUES (11, 'Test Person', '081-234-5678');
Error: UNIQUE constraint failed: customer.phone

NULL isn't equal to anything, not even another NULL, so many rows may have no phone: Anan and Siriporn both have NULL, and the index was made without trouble. If the data already holds repeats, the index can't be made at all. Several customers live in Bangkok:

CREATE UNIQUE INDEX idx_customer_city ON customer (city);
Error: UNIQUE constraint failed: customer.city

An index on several columns: the order matters

An index can hold several columns. Think of a phone book sorted by surname, then first name. Finding "Jaidee, Somchai" is quick; finding every "Jaidee" is quick too, they stand together. But finding everyone whose first name is "Somchai" means reading the whole book: the Somchais are scattered among all the surnames.

An index on (status, ordered) works the same way: by status, and within each status by date.

CREATE INDEX idx_orders_status_ordered ON orders (status, ordered);
SELECT id, customer_id, ordered FROM orders
WHERE status = 'paid' AND ordered >= '2026-11-01';
idcustomer_idordered
1242026-11-05
1362026-11-11
1572026-11-25
3 rows

What SQLite's plan says for three questions:

-- status = 'paid' AND ordered >= '2026-11-01': both columns used
SEARCH orders USING INDEX idx_orders_status_ordered (status=? AND ordered>?)
-- status = 'paid' alone: the first column is enough
SEARCH orders USING INDEX idx_orders_status_ordered (status=?)
-- ordered >= '2026-11-01' alone: the "first names", scattered
SCAN orders

So: put first the columns you test with =, then the one you test with a range (>, <, BETWEEN). An index on (a, b) also serves questions about a alone, so you don't need a separate index on a.

What an index helps, and what it costs

An index helps wherever the database must find rows by a value:

And it costs:

So an index is worth it on columns you look up often, in tables that are big. A table of 50 rows needs none; a column you never search by needs none. A column with only a few different values (status has three) is a weak index on its own: each value still matches a third of the table.

Start with no extra indexes. When a query is slow, look at its plan (Display Plan in Phai Database Studio). If it says SCAN on a big table, an index on the columns in its WHERE or JOIN is the usual cure. Then drop indexes nothing uses.

Expressions that stop an index

An index holds the column's values as they are. If the WHERE wraps the column in a function or a calculation, the database would have to work it out for every row, so it can't use the index:

CREATE INDEX idx_orders_ordered ON orders (ordered);
SELECT id, ordered FROM orders WHERE substr(ordered, 1, 7) = '2026-10';
idordered
52026-10-01
62026-10-03
72026-10-10
82026-10-15
92026-10-22
102026-10-28
6 rows

The same question, with the column left bare:

SELECT id, ordered FROM orders
WHERE ordered >= '2026-10-01' AND ordered < '2026-11-01';
idordered
52026-10-01
62026-10-03
72026-10-10
82026-10-15
92026-10-22
102026-10-28
6 rows

The same 6 rows, but SQLite's plans differ:

-- substr(ordered, 1, 7) = '2026-10'
SCAN orders USING COVERING INDEX idx_orders_ordered
-- ordered >= '2026-10-01' AND ordered < '2026-11-01'
SEARCH orders USING COVERING INDEX idx_orders_ordered (ordered>? AND ordered<?)

(Covering means everything the query needs is in the index itself, so the table isn't read at all. The first still reads the whole index; the second reads only October.)

The usual culprits, and their cures:

Stops the indexUses it
substr(ordered, 1, 7) = '2026-10'ordered >= '2026-10-01' AND ordered < '2026-11-01'
strftime('%Y', joined) = '2025'joined >= '2025-01-01' AND joined < '2026-01-01'
price * 1.07 > 100price > 100 / 1.07
name LIKE '%Chaiya' (starts with %)no cure: search the start of the text, or a text search tool

LIKE 'Pim%' (fixed text before the %) can use an index, but only one that compares without case, COLLATE NOCASE, because LIKE ignores case. With CREATE INDEX idx_customer_city ON customer (city COLLATE NOCASE), city LIKE 'Chiang%' goes straight to that stretch; SQLite's plan says SEARCH ... (city>? AND city<?). GLOB 'Chiang*' minds case, so it can use a plain index.

When you really do search by an expression, the index can hold the expression itself:

CREATE INDEX idx_customer_lower_name ON customer (lower(name));
SELECT id, name FROM customer WHERE lower(name) = 'pim chaiya';
idname
4Pim Chaiya
1 row

SQLite's plan now says SEARCH customer USING INDEX idx_customer_lower_name (<expr>=?). The WHERE must use the very same expression, lower(name).

Don't add an index for every column "just in case". Each one slows down every change to the table and is never used for most queries. Index the columns your slow queries really search by, and check the plan before and after.

DROP INDEX

An index nobody uses only costs. Drop it by name; the table and its rows are untouched:

DROP INDEX idx_orders_status_ordered;
PRAGMA index_list(orders);
seqnameuniqueoriginpartial
0idx_orders_ordered0c0
1idx_orders_customer0c0
2 rows

Indexes that come from the table's own UNIQUE or PRIMARY KEY (the sqlite_autoindex_... ones) can't be dropped this way; they go only when the table is rebuilt without that rule (chapter 23).

  1. Make an index on order_item (product_id), then list order_item's indexes.
  2. This finds the customers who joined in 2025, but can't use an index on joined: WHERE strftime('%Y', joined) = '2025'. Write it so an index could be used, and show their names.
  3. Make a UNIQUE INDEX on product (name), and see its columns with PRAGMA index_info.
Show the answer
CREATE INDEX idx_order_item_product ON order_item (product_id);
PRAGMA index_list(order_item);

SELECT name, joined FROM customer
WHERE joined >= '2025-01-01' AND joined < '2026-01-01';

CREATE UNIQUE INDEX idx_product_name ON product (name);
PRAGMA index_info(idx_product_name);
seqnameuniqueoriginpartial
0idx_order_item_product0c0
1sqlite_autoindex_order_item_11pk0
2 rows
namejoined
Somchai Jaidee2025-01-15
Malee Srisuk2025-03-02
Anan Wongsa2025-04-20
Pim Chaiya2025-06-11
Narin Thongdee2025-08-30
Kanya Boonmee2025-10-05
6 rows
seqnocidname
01name
1 row

Phai (bamboo), given as a gift of knowledge: free to use, learn from and pass on · every example on this page was run on Phai SQL and checked against SQLite when the page was made