Indexing

How database indexes speed up queries, how B-trees, LSM-trees and composite indexes work, what indexes cost on writes, and what interviewers ask.

17 minLesson 2 of 7
On this page
  1. Where an index sits
  2. How indexes are stored
  3. Kinds of index
  4. When the database does not use an index
  5. What an index costs
  6. Secondary indexes in a partitioned database
  7. In the interview
  8. What to practise next

An index is a separate, sorted data structure that a database keeps next to a table so it can find rows by the value of one or more columns without reading the whole table. It is the main tool for making a query fast. The cost is that every insert, update and delete must also change each index on the table, and every index takes disk space and memory.

Without an index on the column in the WHERE clause, the database has to read every row and check it, a full table scan. That is acceptable for a few thousand rows, but on a table with tens of millions of rows a query that should return three rows reads gigabytes of data, and its time grows with the table.

Where an index sits

With an index the database looks up the key in a sorted structure and reads only the matching rows. Without one it scans the whole table.App server to Index (sorted keys) (1. look up key); Index (sorted keys) to Table rows (2. read the rows); App server to Table rows (full scan), asynchronous.App serverIndex (sortedkeys)Table rows1. look up key2. read the rowsfull scan

request and replyasynchronous message

With an index the database looks up the key in a sorted structure and reads only the matching rows. Without one it scans the whole table.

The query planner decides for each query whether to use an index.

How indexes are stored

Almost every index is kept in one of two structures. They differ in how they handle writes, and that difference decides which kind of database suits a workload.

B-tree

A B-tree stores sorted keys in pages of a few kilobytes, with hundreds of keys in each page. The tree is wide and shallow; see balanced trees for the general idea. With about 500 keys per page, three levels hold roughly 125 million entries, so a lookup in a large table reads about three pages. The top levels stay in memory, and because the keys are sorted, range queries and sorted output are cheap.

A write finds the right leaf page and changes it in place. If the page is full it is split in two. Each index therefore costs one random page write per row change. B-trees are the default in most relational databases and suit read-heavy and mixed workloads, but under a very high write rate the random writes become the bottleneck.

LSM-tree

A log-structured merge tree (LSM-tree) never changes data in place. A write goes into a sorted table in memory and an append-only log used for crash recovery. When the in-memory table is full, it is written to disk as a new sorted, immutable file. A background process called compaction merges these files, and it throws away values that were overwritten or deleted.

All disk writes are sequential, so an LSM-tree handles a much higher write rate than a B-tree on the same hardware. The cost falls on reads. A key may be in memory or in any of several files, so a read checks them from newest to oldest. A Bloom filter on each file says when a key is definitely not in it, so most files are skipped. Compaction uses disk and CPU in the background and can cause latency spikes if it falls behind. LSM-trees are common in wide-column and key-value stores for write-heavy data such as events and metrics.

Kinds of index

Primary and secondary indexes

The primary index is built on the primary key. In many databases the table itself is stored in primary key order, so the leaf pages of the primary index hold the rows. This is a clustered index, and a table can have only one. A secondary index is built on any other column, such as email or customer_id. Its entries point back to the row by primary key or by physical location, so a lookup finds the entry first and then fetches the row.

Hash indexes

A hash index applies a hash function to the key and goes straight to the matching bucket. It answers equality lookups such as WHERE token = 'abc' in constant time. The hash scrambles the order of the keys, so it cannot serve range queries, ORDER BY or prefix matches. A B-tree handles equality almost as quickly and also handles everything else, so a hash index is worth choosing only when the access is purely by exact key.

Composite indexes and column order

A composite index covers several columns. An index on (customer_id, created_at) is sorted by customer first, and by date only within each customer, like a phone book sorted by last name and then first name. It is easy to find every customer named Garcia, and almost useless for finding everyone named Maria.

One composite index, two queriesUse the arrows or ← → keys
-- index on (customer_id, created_at)WHERE customer_id = 42 AND created_at >= '03-01'WHERE created_at >= '03-01'
  1. index
    041|03-28
    142|02-11
    242|03-02
    342|03-15
    442|03-27
    543|01-04
    643|03-20
    entries read
    0

    1The entries are sorted by customer and then by date. The first query asks for customer 42 since 1 March.

  2. index
    041|03-28
    142|02-11
    242|03-02start
    342|03-15
    442|03-27
    543|01-04
    643|03-20
    entries read
    1
    matches
    1

    2The tree jumps to the first entry at or after (42, 03-01).

  3. index
    041|03-28
    142|02-11
    242|03-02
    342|03-15
    442|03-27
    543|01-04stop
    643|03-20
    entries read
    4
    matches
    3

    3The scan reads forward, finds two more matches, and stops at the first entry for customer 43. It read 4 entries and found 3 matches.

  4. index
    041|03-28
    142|02-11
    242|03-02
    342|03-15
    442|03-27
    543|01-04
    643|03-20
    entries read
    0

    4The second query asks for every order since 1 March from any customer. Dates are sorted only inside each customer, so the matching entries are scattered.

  5. index
    041|03-28
    142|02-11
    242|03-02
    342|03-15
    442|03-27
    543|01-04
    643|03-20
    entries read
    7
    matches
    5

    5There is no place to jump to, so the database reads every entry. This query needs its own index that starts with created_at.

1 / 5

The rule is to put the columns tested with equality first and then at most one column that is tested with a range or used for sorting. An index on (a, b, c) can serve queries on a, on a and b, and on all three, but not on b alone. This is the leftmost prefix rule.

Covering indexes

When a query needs only columns that are stored in the index, the database can answer it from the index alone and never read the table. This is a covering index. For the orders of customer 42, an index on (customer_id, created_at, total) holds the date and total, so the database skips one random row fetch for each result. It is worth it for a hot query that returns many rows, and the cost is a larger index.

Full-text and geospatial indexes

A B-tree cannot answer "which documents contain this word" or "which points are near this location". Full-text search uses an inverted index from each word to the documents containing it, covered in search systems. Location queries use geohashes or quadtrees, covered in Design Proximity Search.

When the database does not use an index

An index that exists is not always used, and "why is this query still slow?" is a common interview question. There are three typical causes, and each has a different fix.

Low selectivity

An index on status, with five possible values, returns a fifth of the table for status = 'shipped'. Following the index means one random row fetch per match, which is slower than reading the table sequentially once, so the planner scans the table and ignores the index. An index on a column helps when the condition matches a small share of the rows. For such a column, put it in a composite index behind a more selective column, or use a partial index that covers only a rare value such as status = 'pending'.

A function applied to the column

An index on email is sorted by the stored value. The condition WHERE LOWER(email) = 'a@b.com' asks about a different value, so the database cannot use the sort order and scans the table. WHERE DATE(created_at) = '2026-03-01' fails for the same reason, and so does comparing a column to a value of a different type. Either rewrite the condition so the column stands alone, as in created_at >= '2026-03-01' AND created_at < '2026-03-02', or build an index on the expression itself if the database supports it.

A leading wildcard

An index on name helps LIKE 'Gar%', because all matching names are next to each other in sorted order. It does not help LIKE '%arcia', because a match can appear anywhere in the order. For substring search, use a full-text index instead.

What an index costs

Every index is updated by every insert and delete on the table, and by every update that changes an indexed column. A table with a primary key and three secondary indexes does four index updates for each inserted row. On a B-tree each is a random page write, so write throughput falls as indexes are added. The indexes also take disk space and compete with table data for memory.

Drop indexes that no query uses. Building an index on a large live table reads the whole table, so it is normally run during a quiet period.

Secondary indexes in a partitioned database

When a table is split across shards (see sharding and partitioning), a secondary index has to decide where its entries live. There are two designs.

Local secondary index

Each shard keeps an index only for its own rows. Writes are cheap, because a row and its index entries are updated on the same shard in one operation. A query that filters by the indexed column does not know which shard holds the match, so it must ask every shard and merge the answers. This scatter-gather read is as slow as the slowest shard.

Global secondary index

The index is itself partitioned by the indexed value, so all entries for one email address sit on one index shard. A query by that column reads a single shard. The cost moves to writes: a row lives on one shard, but its index entries live on others, so one write touches several shards. These updates are usually asynchronous, so a read through the index may briefly miss a row that was just written. Choose a global index when reads by the indexed column are frequent and a short lag is acceptable.

In the interview

Bring up indexes right after you list the access patterns of the design. For each hot query, name the index and its column order, and say what it costs. Choose a B-tree unless writes dominate, in which case pick a store built on an LSM-tree, and give the reason in one sentence.

Questions to expect:

  • "Why not index every column?" Each index slows every write and takes space and memory. Index the columns in the filters and sort orders of real queries, and remove the rest.
  • "What order do the columns of a composite index go in?" Columns compared with equality come first and a range or sort column comes last. The index serves any leftmost prefix of its columns, so it cannot be used for a query that skips the first column. When two columns are both tested with equality, either order serves that query equally well, so choose the order that also lets the index serve other queries through its leftmost prefix.
  • "There is an index on the column and the query is still slow. Why?" Look at the query plan, and check for low selectivity, a function on the column, a leading wildcard or a type mismatch.
  • "B-tree or LSM-tree?" A B-tree gives fast, predictable reads and is the default. An LSM-tree turns random writes into sequential ones for a very high write rate, and pays with slower reads and compaction.
  • "How do secondary indexes work when the data is sharded?" A local index is cheap to write but forces queries to ask every shard. A global index sends a query to one shard but makes each write update other shards, usually asynchronously, so it can lag.
  • "A table has a very high write rate and many indexes. What do you do?" Remove every index that no query needs, because each one adds a write to every insert. If the write rate is still too high, move the data to a store built on an LSM-tree, which turns the index writes into sequential ones, and accept slower reads and background compaction.
Indexing an order historyStrong answer
Interviewer

Users see their orders, newest first, 20 per page. How do you keep that fast?

You

The query filters by customer and sorts by date, so I would index (customer_id, created_at DESC). The database jumps to that customer's section and reads 20 entries in order, with no scan and no separate sort. If the page shows only the date and the total, I would add total to the index so that it covers the query.

Interviewer

Support also searches orders by status. Should we add an index on status?

You

Not on its own. There are only a few statuses, so a value like shipped matches a large share of the table and the planner would scan anyway. If support always filters by status within a date range, I would use (status, created_at). If they only look for rare open orders, a partial index on those rows is smaller.

Quick check

A table has an index on (country, city, signup_date). Which query can use it best?

The query is WHERE LOWER(email) = 'a@b.com' and there is an index on email. What is the best fix?

A sharded table needs frequent lookups by email, which is not the shard key. A short delay before a new row appears in the lookup is acceptable. What fits best?

What to practise next

Read Replication next to see how copies of a table are kept on several machines. Design Typeahead Search uses prefix lookups on an index.