Sub topic 14
Indexes and the cost of speed
This chapter assumes you can write SELECT queries with WHERE, JOIN, and ORDER BY. It also assumes you know what primary keys and foreign keys are, as covered in earlier chapters. By the end you should be able to explain what an index is, create one, predict when the database will use it, and weigh its cost against its benefit.
The problem: finding rows without a map
Suppose the orders table from earlier chapters holds ten million rows. You run this query:
SELECT order_id, order_date, total_amount
FROM orders
WHERE customer_id = 1;Without help, the database has only one option. It reads every row in the table and checks whether customer_id equals 1. This is called a full table scan (or sequential scan). The work grows in proportion to the table size. If the table doubles, the scan takes about twice as long, even when the query returns only three rows.
An index is a separate data structure that the database maintains alongside a table. It stores the values of one or more columns in a form that is quick to search, and each entry points back to the row that holds the value. It works like the index at the back of a book. You look up a term, find the page numbers, and jump to those pages instead of reading the whole book.
How an index works internally
Most relational databases build indexes as B-trees (more precisely, B+ trees in many systems). A B-tree keeps the indexed values in sorted order, arranged as a shallow, wide tree.
- The top node (the root) holds ranges that tell the search which child node to visit next.
- Intermediate nodes narrow the range further.
- Leaf nodes at the bottom hold the actual indexed values in sorted order, each with a pointer to the table row.
Because each node holds many entries, the tree stays very shallow. An index on ten million rows is often only three or four levels deep. A lookup reads a handful of nodes rather than millions of rows. The cost grows with the logarithm of the table size, so a table that is a thousand times larger needs only a few more steps.
Since the leaf level is sorted, a B-tree helps with more than equality. It also speeds up range conditions (>, <, BETWEEN), prefix matches such as LIKE 'Ada%', and ORDER BY on the indexed column, because the database can read entries already in order.
Creating an index
The statement from the topic plan creates an index on the foreign key column:
CREATE INDEX idx_orders_customer_id ON orders (customer_id);After this, the database keeps idx_orders_customer_id in step with the orders table. You do not change your queries. The query planner (also called the optimizer) decides on its own whether to use the index. Most systems let you inspect that decision with EXPLAIN:
EXPLAIN
SELECT order_id, order_date, total_amount
FROM orders
WHERE customer_id = 1;The output format differs by system. In PostgreSQL, you would see an Index Scan or Bitmap Heap Scan node when the index is used and a Seq Scan node when it is not. Always check the plan rather than assuming an index is used.
Indexes you already have
You do not need to create every index by hand. Databases create some automatically:
- A
PRIMARY KEYconstraint creates a unique index on the key columns. - A
UNIQUEconstraint creates a unique index, because the database needs a fast way to check whether a value already exists. - A
FOREIGN KEYconstraint does not create an index on the referencing column in PostgreSQL and SQLite. MySQL's InnoDB engine does create one if none exists.
That last point matters. In the orders table, customer_id references customers. Joins from customers to orders, and deletes of a customer row, both need to find matching orders. Without an index on orders.customer_id, each of those operations may scan the whole orders table. Indexing foreign key columns is a common first step in tuning.
The cost of speed
An index is not free. It trades write speed and storage for read speed.
| Aspect | Effect of adding an index |
|---|---|
| Reads that match the indexed columns | Faster, often by orders of magnitude on large tables |
| `INSERT` | Slower, because each index needs a new entry |
| `UPDATE` of an indexed column | Slower, because the old entry is removed and a new one added |
| `DELETE` | Slower, because entries are removed from every index |
| Disk and memory | Each index uses space, sometimes close to the size of the indexed columns in the table |
| Planning | More indexes give the planner more options to evaluate |
A table with ten indexes must update eleven structures for each inserted row: the table and ten indexes. For a read-heavy reporting table that is usually acceptable. For a table that receives thousands of writes per second, extra indexes can become the bottleneck.
The rule of thumb is to index for the queries you actually run. An index nobody uses still costs you on every write.
Choosing what to index
Good candidates:
- Foreign key columns used in joins.
- Columns that appear often in
WHEREconditions and filter out most rows. - Columns used for
ORDER BYon large result sets.
Poor candidates:
- Tiny tables. A scan of a few hundred rows is as fast as an index lookup.
- Columns with very few distinct values, such as a boolean
is_active. The index matches so many rows that a scan is cheaper. The measure of how well a column separates rows is called selectivity. High selectivity (many distinct values) makes an index useful. - Columns that are updated constantly and rarely searched.
Composite indexes and column order
An index can cover several columns. Suppose you often run this query:
SELECT order_id, total_amount
FROM orders
WHERE customer_id = 1
AND order_date >= '2026-01-01';A composite index on both columns serves it well:
CREATE INDEX idx_orders_customer_date
ON orders (customer_id, order_date);The order of columns matters. The index is sorted by customer_id first, then by order_date within each customer. This index can serve:
- Filters on
customer_idalone. - Filters on
customer_idandorder_datetogether.
It generally cannot serve a filter on order_date alone, because dates are not sorted globally in the index, only within each customer. This is the leftmost prefix rule. Put the column used with equality conditions first, and the column used with a range condition after it.
With this composite index in place, the separate index on customer_id is mostly redundant, since the composite index already serves customer_id-only lookups. Redundant indexes add write cost with little benefit.
Why the database sometimes ignores your index
You created an index and EXPLAIN still shows a full scan. Common causes:
- A function wraps the column.
WHERE YEAR(order_date) = 2026cannot use a plain index onorder_date, because the index stores dates, not years. Rewrite it as a range:WHERE order_date >= '2026-01-01' AND order_date < '2027-01-01'. - A leading wildcard.
LIKE '%son'cannot use a B-tree, because the sorted order starts from the first character. - Low selectivity. If the condition matches a large share of the table, the planner correctly prefers a scan.
- Type mismatch. Comparing an integer column to a string value may force a conversion on every row in some systems.
- Stale statistics. The planner chooses based on statistics about the data. After a large load, run the system's statistics command (
ANALYZEin PostgreSQL and SQLite) so its estimates are accurate. - Wrong column order in a composite index, as described above.
Unique indexes
A unique index rejects duplicate values, which makes it another way to enforce integrity:
CREATE UNIQUE INDEX idx_customers_email ON customers (email);In the schema from earlier chapters, email already has a UNIQUE constraint, so this index would be redundant there. The example shows the idea: a unique constraint is implemented by a unique index. Prefer declaring the constraint when the rule is part of your data model, because it states the intent in the schema.
Indexes and the other chapters
Indexes do not change what a query returns. They change only how fast it returns. That is why they are the last topic in this tutorial: you design tables, keys, and constraints for correctness first, then add indexes for the queries that prove slow. Transactions still guarantee atomicity with or without indexes, and joins still match foreign keys to primary keys. The index only gives the database a quicker route to the rows.
Exercise
The table orders has 20 million rows and receives about 5,000 inserts per second. A report runs SELECT * FROM orders WHERE order_date = '2026-03-01' once a day and takes 40 seconds. Your colleague proposes adding six indexes on different columns "to be safe". What would you do instead, and why?
Show answer
Add at most one index, on order_date, and verify with EXPLAIN that the report query uses it. Six speculative indexes would make each of the 5,000 inserts per second update six more structures, slowing writes and using extra storage, while helping queries that nobody runs. A single daily report is also a reason to consider whether 40 seconds is acceptable at all, or whether running it against a read replica avoids the write cost entirely.
Exercise
A composite index exists on orders (customer_id, order_date). Which of these queries can use it efficiently: (a) WHERE customer_id = 7, (b) WHERE customer_id = 7 AND order_date >= '2026-01-01', (c) WHERE order_date >= '2026-01-01'?
Show answer
Queries (a) and (b). Both filter on the leftmost column, customer_id. Query (c) filters only on the second column, so it cannot use the index's sort order effectively and will usually fall back to a scan, unless a separate index on order_date exists.