34. Making queries fast

How a database finds the rows you ask for, where an index helps, and the small habits that keep queries fast even with millions of rows.

How a database finds rows

Our practice shop has only 10 customers, so every statement is quick. A real shop may have a hundred thousand customers and a million orders, and then two statements that differ only a little can differ a thousandfold in speed. This chapter is about why.

When you ask "which customers live in Phuket?", the database has two ways to find out:

SELECT id, name FROM customer WHERE city = 'Phuket';
idname
4Pim Chaiya
8Siriporn Kaewdee
2 rows

Both ways give the same result, 2 customers; only the speed differs. SQL doesn't let you choose the way yourself: the database looks at which indexes it has and makes its own query plan. Your part is to have the right indexes and to write statements an index can help.

Finding a row by its table's id is always fast: an INTEGER PRIMARY KEY is the order the table keeps its rows in, so no extra index is needed:

SELECT name, price FROM product WHERE id = 5;
nameprice
Banana Bread60.0
1 row

Seeing the plan

In SQLite, EXPLAIN QUERY PLAN tells you a query's plan. Phai SQL doesn't have that statement yet (it is an error), so this example is shown, not run:

EXPLAIN QUERY PLAN SELECT id, name FROM customer WHERE city = 'Phuket';

With no index yet, the plan says every row of customer has to be read:

SCAN customer

Phai Database Studio shows the plan for a Phai SQL file: type the query in the SQL tab and press Plan (or Table > Display Plan, Ctrl+L). It shows the plan without running the query, in the same words SQLite uses:

In the planMeans
SCAN customerevery row of the table is read
SEARCH customer USING INDEX customer_city (city=?)found through the index customer_city
SEARCH product USING INTEGER PRIMARY KEY (rowid=?)found straight by id
USING COVERING INDEXevery column asked for is in the index: the table isn't opened at all
USE TEMP B-TREE FOR ORDER BYthe rows are sorted after they are read (no index has them in order)

The plans in this chapter are the ones SQLite makes. Phai SQL makes its own; mostly they are the same, but for some queries it may choose differently. For the real plan on your own file, use Display Plan.

Indexes for WHERE, JOIN and ORDER BY

Chapter 25 showed how to make an index; here is where to put one. The simple rule: index the columns you search by often. They are usually in three places:

  1. Columns in WHERE that you filter by often, such as city.
  2. Columns a JOIN uses to find rows in another table, above all foreign keys, such as orders.customer_id and order_item.product_id.
  3. Columns in ORDER BY that you sort by often, such as orders.ordered (the order's day).
CREATE INDEX customer_city ON customer(city);
CREATE INDEX orders_customer ON orders(customer_id);
CREATE INDEX order_item_product ON order_item(product_id);
CREATE INDEX orders_ordered ON orders(ordered);
✓ Done

Now the Phuket query no longer reads every row. Its plan becomes:

SEARCH customer USING INDEX customer_city (city=?)

For a JOIN, a database usually reads one table and, for each of its rows, looks for the matching rows in the other. When the table being looked into has an index, each look is quick. For example, "which orders had Coffee in them?":

SELECT p.name, oi.order_id, oi.qty
FROM product AS p
JOIN order_item AS oi ON oi.product_id = p.id
WHERE p.id = 1
ORDER BY oi.order_id;
nameorder_idqty
Coffee12
Coffee31
Coffee71
Coffee92
Coffee121
5 rows

Coffee is in 5 orders. The plan finds the product by id, then the rows of order_item through the new index:

SEARCH p USING INTEGER PRIMARY KEY (rowid=?)
SEARCH oi USING INDEX order_item_product (product_id=?)
USE TEMP B-TREE FOR ORDER BY

The last line says the rows found are then sorted by order_id. That's fine: only the few rows found are sorted.

Without order_item_product, the second line would be SCAN oi: every item of every order read.

An index helps ORDER BY too: it keeps its values in order already, so the database can read along the index instead of sorting. The 3 latest orders:

SELECT id, ordered, status FROM orders ORDER BY ordered DESC LIMIT 3;
idorderedstatus
152026-11-25paid
142026-11-18cancelled
132026-11-11paid
3 rows
SCAN orders USING INDEX orders_ordered

Don't index every column. Each index has to be changed whenever a row is added, changed or deleted, so writes get slower and the file bigger. Index only the columns you really search by; a small table of a few hundred rows is fast without any index.

Writing a WHERE an index can help

An index keeps a column's values as they are stored, in order. Put the column through a function or a calculation before comparing it, and the index can't be used: the values you compare aren't the ones the index has in order, so the database works them out row by row.

The orders of October 2026 can be asked for in two ways that give the same 6 orders:

-- Every row read: substr() on the column keeps the index out
SELECT id, ordered FROM orders
WHERE substr(ordered, 1, 7) = '2026-10'
ORDER BY id;
idordered
52026-10-01
62026-10-03
72026-10-10
82026-10-15
92026-10-22
102026-10-28
6 rows
-- The index orders_ordered can help: the bare column compared to a range
SELECT id, ordered FROM orders
WHERE ordered >= '2026-10-01' AND ordered < '2026-11-01'
ORDER BY id;
idordered
52026-10-01
62026-10-03
72026-10-10
82026-10-15
92026-10-22
102026-10-28
6 rows

The first one's plan is SCAN orders; the second's is SEARCH orders USING COVERING INDEX orders_ordered (ordered>? AND ordered<?) (covering, because id and ordered are both in the index). The way to remember it: leave the column alone on one side of the comparison, and do the working out on the other side.

The same goes for LIKE:

SELECT name, city FROM customer WHERE city LIKE 'Ph%';
namecity
Pim ChaiyaPhuket
Siriporn KaewdeePhuket
2 rows
SELECT name, city FROM customer WHERE city LIKE '%et';
namecity
Pim ChaiyaPhuket
Siriporn KaewdeePhuket
2 rows

Both find the same 2 Phuket customers, but with a lot of data only the "starts with" one has a chance to be fast.

LIKE ignores the case of English letters, so SQLite uses an index for LIKE 'Ph%' only when that index was made with COLLATE NOCASE. Phai SQL today reads every row for a LIKE. For a fast "starts with" search on both, write a range instead: city >= 'Ph' AND city < 'Pi' uses an ordinary index (but, unlike LIKE, it minds upper and lower case).

SELECT name, city FROM customer WHERE city >= 'Ph' AND city < 'Pi';
namecity
Pim ChaiyaPhuket
Siriporn KaewdeePhuket
2 rows

Ask only for what you use

The less the database has to read, copy and send, the sooner the answer comes. Three habits help a lot:

Name only the columns you use instead of SELECT *. Less data comes back, and sometimes every column you ask for is in an index, so the table isn't opened at all (the plan says COVERING INDEX). This query asks only for city, which customer_city holds:

SELECT DISTINCT city FROM customer ORDER BY city;
city
Bangkok
Chiang Mai
Khon Kaen
Phuket
4 rows

Add LIMIT when you want only a few rows, such as the first page of a list or a "top 5". With an index already in the ORDER BY's order, the database reads the first few rows and stops (as for the 3 latest orders above).

Ask "is there any?" with EXISTS, not by counting. To know whether customer 1 has ever ordered, count(*) has to count every order, while EXISTS stops at the first one it finds:

-- Count them all, then see whether it is more than 0
SELECT (SELECT count(*) FROM orders WHERE customer_id = 1) > 0 AS has_orders;
has_orders
1
1 row
-- The first one found is the answer
SELECT EXISTS (SELECT 1 FROM orders WHERE customer_id = 1) AS has_orders;
has_orders
1
1 row

Both answer 1 (yes). Customer 1 has 3 orders, so it makes little difference here, but for a customer with ten thousand, EXISTS looks at one. It works the same way in a WHERE, for example the customers who have ordered:

SELECT name FROM customer AS c
WHERE EXISTS (SELECT 1 FROM orders AS o WHERE o.customer_id = c.id)
ORDER BY c.id;
name
Somchai Jaidee
Malee Srisuk
Anan Wongsa
Pim Chaiya
Narin Thongdee
Kanya Boonmee
Wichai Saelim
Siriporn Kaewdee
8 rows

8 of the 10 customers have ordered; customers 9 and 10 haven't yet.

Many INSERTs in one transaction

Whenever data changes, the database has to write it to disk so that it is sure not to be lost, even if the power goes off right then. That sure write (waiting until the disk says it has kept the data) is far slower than any work done in memory.

Without your own BEGIN, each INSERT is a transaction of its own: 10,000 rows added by 10,000 statements means 10,000 sure writes. Put them inside BEGIN ... COMMIT (chapter 19) and they are one transaction, written for sure once, at the COMMIT, which is many times faster:

BEGIN;
INSERT INTO category (name) VALUES ('Fruit');
INSERT INTO category (name) VALUES ('Frozen');
INSERT INTO category (name) VALUES ('Household');
COMMIT;
SELECT id, name FROM category ORDER BY id;
idname
1Drinks
2Bakery
3Snacks
4Stationery
5Fruit
6Frozen
7Household
7 rows

Three new categories, 7 in all. There is a second gain: if a row goes wrong halfway, ROLLBACK and none of them went in. Nothing is left half done.

One INSERT with many rows in its VALUES, or an INSERT ... SELECT, is a single transaction too:

INSERT INTO category (name) VALUES ('Pet'), ('Garden');
✓ 2 rows changed

A program that loads data from a file, such as a CSV of ten thousand rows, should BEGIN before its loop of INSERTs and COMMIT once at the end. With millions of rows, a COMMIT every ten thousand rows is fine: just not a disk write for every row.

VACUUM: packing the file

Delete a lot of rows and the database file doesn't shrink by itself: the free space is kept for new data later, and the data may end up scattered through the file. VACUUM writes the whole database out again, packed and in order, so the file is only as big as its data:

VACUUM;
✓ Done

VACUUM doesn't change a single row, but it reads and writes the whole file: on a big file it takes a while, and other programs can't write meanwhile. Do it now and then, for example after deleting a lot of old data, at a time when nobody is working. It isn't a daily job.

  1. Find the customers who joined in 2026 (joined) without putting a function on joined, so that an index can help (make an index on joined too). Sort by id.
  2. Ask whether any product is sold out (stock = 0), with EXISTS.
  3. Add the categories Toys and Books in one transaction, then count the categories.
Show the answer
CREATE INDEX customer_joined ON customer(joined);
SELECT id, name, joined FROM customer
WHERE joined >= '2026-01-01' AND joined < '2027-01-01'
ORDER BY id;

SELECT EXISTS (SELECT 1 FROM product WHERE stock = 0) AS sold_out;

BEGIN;
INSERT INTO category (name) VALUES ('Toys');
INSERT INTO category (name) VALUES ('Books');
COMMIT;
SELECT count(*) FROM category;
idnamejoined
7Wichai Saelim2026-01-09
8Siriporn Kaewdee2026-02-14
9Tawan Rungruang2026-05-21
10Lalita Meesuk2026-08-03
4 rows
sold_out
1
1 row
count(*)
11
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