Sub topic 2
What an Index Is and What It Trades
This chapter assumes you can write SELECT, WHERE, ORDER BY and JOIN queries. It also assumes you know what rows, columns and primary keys are, and that you can tell linear growth from logarithmic growth. The examples use PostgreSQL syntax. The ideas carry over to MySQL, SQL Server and Oracle, though details differ.
What an index is
An index is a separate data structure that the database keeps next to a table. It stores the values of one or more columns, organized so the database can find matching values quickly. Each entry also holds a pointer to the table row that contains the value.
A book index works the same way. To find every page that mentions "replication", you look up the word in the alphabetical index at the back and jump to the listed pages. Without it, you read every page.
Three properties matter for everything that follows:
- The index is redundant data. It copies column values out of the table. Nothing is stored in the index that the table does not already hold, apart from the pointers.
- The database maintains it automatically. You never update an index by hand. Every change to the table is applied to the index too.
- It changes speed, not results. A query returns the same rows with or without an index. Only the work needed to produce them changes.
Why scanning is the baseline
Without a usable index, the database reads the table from start to finish and tests each row against the WHERE condition. This is a sequential scan. Its cost grows linearly with table size, so a table ten times larger takes about ten times longer to scan.
An index lets the database find the first matching entry in time proportional to the logarithm of the table size. A B-tree is the usual structure for this, and a later chapter covers its internals. For now, treat the index as a structure that answers "where are the rows with customer_id = 42?" in a handful of page reads. It does not need to read the whole table.
A worked example
The following script builds a table with a million rows and compares the plan before and after adding an index. The data is synthetic.
CREATE TABLE orders (
id bigint PRIMARY KEY,
customer_id bigint NOT NULL,
status text NOT NULL,
created_at timestamptz NOT NULL,
total_cents integer NOT NULL
);
INSERT INTO orders
SELECT g,
(random() * 10000)::bigint,
(ARRAY['open', 'shipped', 'cancelled'])[(g % 3) + 1],
now() - make_interval(mins => g),
(random() * 50000)::int
FROM generate_series(1, 1000000) AS g;
ANALYZE orders;
-- Before: no index on customer_id.
EXPLAIN SELECT * FROM orders WHERE customer_id = 42;
CREATE INDEX orders_customer_id_idx ON orders (customer_id);
ANALYZE orders;
-- After: the planner can choose the index.
EXPLAIN SELECT * FROM orders WHERE customer_id = 42;The first plan shows a Seq Scan on orders. The second usually shows a Bitmap Heap Scan fed by a Bitmap Index Scan on orders_customer_id_idx, or a plain Index Scan. Which one appears depends on how many rows match. Each customer has about 100 orders out of a million, so the database reads roughly 0.01% of the table instead of all of it. The ANALYZE commands refresh the statistics the planner uses to choose a plan. A later chapter on query plans explains that choice.
The id column already has an index. The PRIMARY KEY constraint creates one automatically, which is why a lookup by id needs no extra work.
The first trade: reads get faster, writes get slower
An index speeds up reads because it is a second copy of data kept in a searchable order. That copy must always agree with the table, and keeping it in agreement is the price.
| Operation | Effect of each additional index |
|---|---|
| `INSERT` | A new entry is added to every index on the table. |
| `DELETE` | Entries are marked dead in every index. Space is reclaimed later. |
| `UPDATE` of an indexed column | The old entry is retired and a new one is inserted. |
| `UPDATE` of non-indexed columns only | Often cheap. PostgreSQL can skip index changes if the new row version fits on the same page and no indexed column changed (a "HOT" update). |
| `SELECT` | Can be much faster if the planner uses the index. No cost if it does not. |
A table with one index and a table with eight pay very different write costs. A workload that mostly loads or updates data, such as an event log, feels this more than one that mostly reads. A table with ten indexes does roughly ten times the index work on every insert.
The second trade: storage
Each index occupies disk space and competes for memory. The database keeps frequently used pages in a cache, and index pages share that cache with table pages. A large, rarely used index can push useful pages out.
You can measure the cost directly:
SELECT pg_size_pretty(pg_relation_size('orders')) AS table_size,
pg_size_pretty(pg_relation_size('orders_customer_id_idx')) AS index_size;An index on a narrow column is smaller than the table, but not negligible. In a table with few columns, the index on one column can be a large fraction of the table. Wide columns, such as long text, make bigger indexes. Composite indexes, covered in a later chapter, are bigger still.
The third trade: the planner has to choose
Creating an index does not force the database to use it. The query planner estimates the cost of each possible plan and picks the cheapest. If a query needs most of the table, a sequential scan can be cheaper than jumping through an index for every row, because sequential reads are faster than scattered ones. An index that no plan ever picks costs space and write time and returns nothing.
The planner also adds a small cost of its own. More indexes mean more candidate plans to consider, though this rarely matters at ordinary index counts.
Costs you may not expect
- Creating an index locks or loads the table. A plain
CREATE INDEXin PostgreSQL blocks writes to the table while it builds. On a busy production table, useCREATE INDEX CONCURRENTLY, which avoids that lock but takes longer and cannot run inside a transaction block. - Indexes carry maintenance debt. After many updates and deletes, an index can contain dead entries and wasted space. This is called bloat. A later chapter covers statistics and maintenance.
- Indexes can hurt a query. A bad statistic or a poorly chosen index can lead the planner to a slower plan than a sequential scan. This is uncommon, but it explains why you verify with
EXPLAINinstead of assuming.
Common mistakes
- Indexing every column. This multiplies write cost and storage for little read benefit.
- Indexing without a query in mind. An index is justified by a query it speeds up, not by a column looking important.
- Assuming an index is used. You confirm with
EXPLAIN. Several ways of writing a predicate prevent index use, and a later chapter covers them. - Forgetting that the primary key is already indexed. A second index on the same column is pure overhead.
- Judging by small test data. On a table of a few hundred rows, a sequential scan is often the fastest plan, and the planner will correctly ignore your index. Test with realistic volumes.
Summary of the model
An index is a maintained, sorted copy of selected columns with pointers to rows. It turns a linear scan into a logarithmic search for the queries it fits. You pay for that with slower writes, extra storage, cache pressure and maintenance. Whether it is worth it depends on how often the queries run, how selective they are, and how write-heavy the table is.
Exercise
A table receives 5,000 inserts per second and is queried a few times per day by an analyst who filters on a column with no index. A colleague proposes adding five indexes "to make queries faster". Which side of the trade-off does this table's workload favor, and what would you do?
Show answer
The workload is write-heavy and read-light, so it favors few indexes. Each extra index adds work to every one of the 5,000 inserts per second and uses storage, while only a handful of queries would benefit. Avoid adding five indexes. If the analyst's query is too slow, add at most one index for that specific query and measure its effect on insert throughput. Alternatively, run the analysis against a read replica or a separate reporting copy.
Exercise
You create an index on orders (status), where 90% of rows have status = 'shipped'. EXPLAIN SELECT * FROM orders WHERE status = 'shipped' still shows a sequential scan. Is this a bug?
Show answer
No. The query returns most of the table, so reading every page in order is cheaper than visiting the index and then fetching 90% of the rows in scattered order. The planner correctly chose the cheaper plan. The index may still help for rare values such as status = 'cancelled'.