System Design

Core Concepts

Indexing and Query Performance

An index does not make a query fast. It makes one access path cheap, and three separate things have to go right before that helps: the path has to exist, the query has to be able to use it, and the planner has to choose it.

Why you are doing this at all

"Add an index" is the most common answer to a slow query, and it works often enough that people stop asking why. Then one day the index is there, the query is still slow, and you have no next move.

Here is a way of looking at it that gives you one.

An index is a second copy of one part of your data, kept sorted, and you pay for it on every write. It does not make queries fast. It makes one specific access path cheap. An access path is the route the database takes to find rows: reading the whole table, or going through one particular index. Whether a query gets faster depends on three separate things going right, and each one can fail on its own.

  1. The path has to exist. There is an index that could answer the query.
  2. The query has to be able to use it. This depends on how the predicate, the condition in the WHERE clause, is written. It's easy to write one that can't use the index.
  3. The planner has to choose it. The planner is the part of the database that decides how to run a query. It chooses from cost estimates built on statistics about your data. If those statistics are wrong, it picks a worse plan and has no way to know.

Most cases of "I added an index and nothing happened" are failure two or three. People keep adding indexes, which only fixes failure one. Each new index makes every write slower, and the real cause is still there.

The trade you are making

Every index adds work to every write. If you insert a row into a table with five indexes, the database does six writes: the row itself, plus a new entry in the right place in each of the five sorted indexes. Deletes cost about the same. An update can cost twice per index, once to remove the old entry and once to add the new one.

So the question is never "would an index help this query?" It is "which access path am I buying, and what will it cost on every write to this table, forever?"

When to skip this

If the table is small, stop. A table of a few thousand rows sits in memory, and scanning all of it takes very little time, so an index saves almost nothing. That is why the planner often ignores an index on a small table, and it's right to.

The rough threshold isn't a row count. It is whether the table's working set stays in the buffer pool. The working set is the part of the table your queries touch regularly. The buffer pool is the database's in-memory cache of pages, the fixed-size blocks it stores data in. Once reads start going to disk, the gap between reading four pages and reading forty thousand decides how fast the query is. Below that point, most index work makes no difference you could measure.

The toolkit

What an index actually is

Almost every general-purpose index is a B-tree: a sorted tree that is shallow and wide. Internal pages hold separator keys, which say which child page covers which range of values, and pointers to those child pages. Leaf pages hold the indexed values in order, and each value has a pointer to its row in the table.

The important property is how shallow the tree is. It's worth working out, because the result surprises people.

Back of envelopeWhy an index lookup costs the same on a big table
A page is 8 KB. An entry is the key plus a pointer,
call it 22 bytes for a bigint key.

  entries per page      8192 / 22     ≈  370

So each level multiplies reachable rows by ~370:

  depth 1 (root only)                 370 rows
  depth 2                             137,000
  depth 3                                    50M
  depth 4                                    18B

⇒ A B-tree over 50 million rows is 3 levels deep.
⇒ Over 18 billion rows it is 4.

A point lookup therefore reads 3 or 4 pages, and the
upper levels are almost always cached because every
lookup touches them.

Compare the full scan of that 50 million row table:
  row size 200 bytes ⇒ 10 GB ⇒ ~1.2 million pages

  index lookup      3 to 4 pages
  full scan         1,200,000 pages

  ⇒ five to six orders of magnitude

And the shape of that result: growing the table by 100x
adds ONE page read. Index lookup cost is essentially
flat in table size, which is the whole reason the
structure is worth its write cost.
A lookup in a B-tree
The lookup for 142 starts at the root (1), follows the separators to an internal page (2), and lands on a leaf (3). The leaf entry points at the row's page in the table (4). Every lookup reads the root and one internal page, so the upper levels are almost always in memory. The arrows between the leaves link each leaf to the next one in key order.The lookup for 142 starts at the root (1), follows the separators to an internal page (2), and lands on a leaf (3). The leaf entry points at the row's page in the table (4). Every lookup reads the root and one internal page, so the upper levels are almost always in memory. The arrows between the leaves link each leaf to the next one in key order.
A lookup reads one page per level, then the row. The lookup for 142 starts at the root (1), follows the separators to an internal page (2), and lands on a leaf (3). The leaf entry points at the row's page in the table (4). Every lookup reads the root and one internal page, so the upper levels are almost always in memory. The arrows between the leaves link each leaf to the next one in key order.

The picture shows two more things, and people often miss both.

Leaves are linked, so an index gives you order for free. A range query finds its first leaf and then walks sideways along the leaves, without going back to the root. An ORDER BY on the indexed column needs no sort at all, because the entries are already in order. This is why a B-tree beats a hash index for almost everything, even though a hash index is faster for a pure equality lookup.

The leaf points at the row, so most index scans read twice. The database finds the entry in the index, then fetches the row from the table to get the columns you asked for. That second read goes to a random place in the table, and at scale it's the expensive half.

The access paths, and what each costs

The planner chooses between a small number of plan shapes. If you know them by name, you can read most of a plan.

pathwhat it doesgood when
sequential scanread every page in orderyou want most of the table, or the table is small
index scanwalk the index, fetch each rowyou want few rows, and you want them in index order
index-only scananswer entirely from the index, never touch the rowthe index contains every column the query needs
bitmap scancollect row locations from the index, sort them, then read the table in page orderyou want a middling number of rows and random fetches would thrash
nested loop joinfor each row on the left, look up the rightthe left side is small and the right side is indexed
hash joinbuild a hash of one side, stream the otherboth sides are large and there is no useful index
merge joinwalk two sorted inputs togetherboth sides are already sorted, usually by an index

A sequential scan is not a failure. It's the correct plan for a query that wants half the table. If you treat every scan in a plan as a bug, you end up adding indexes that make writes slower and reads no faster.

Selectivity, and the point where an index stops helping

A scan can win because an index scan does random reads and a sequential scan does sequential ones, and the hardware cares a lot about the difference. A random read jumps to wherever the next matching row lives. A sequential read takes the pages in order, one after another.

How three plans read the same table
The table has ten pages, and the query matches five rows on pages 2, 5, 7 and 9, in green. The sequential scan reads all ten pages once, left to right. The index scan fetches rows in index order, so it jumps from page 7 to 2 to 9 to 5 and back to 2, and reads page 2 twice. The bitmap scan collects the page numbers first, sorts them, and reads each of the four pages once, in order.The table has ten pages, and the query matches five rows on pages 2, 5, 7 and 9, in green. The sequential scan reads all ten pages once, left to right. The index scan fetches rows in index order, so it jumps from page 7 to 2 to 9 to 5 and back to 2, and reads page 2 twice. The bitmap scan collects the page numbers first, sorts them, and reads each of the four pages once, in order.
Only the index scan jumps around the table. The table has ten pages, and the query matches five rows on pages 2, 5, 7 and 9, in green. The sequential scan reads all ten pages once, left to right. The index scan fetches rows in index order, so it jumps from page 7 to 2 to 9 to 5 and back to 2, and reads page 2 twice. The bitmap scan collects the page numbers first, sorts them, and reads each of the four pages once, in order.

Selectivity is the share of the table's rows that a query matches. If a query matches 1 percent of rows, the index reads about 1 percent of the rows, one at a time, and skips the rest. If it matches 40 percent, the index reads 40 percent of the rows in random order. On spinning disks that was a disaster. On SSDs it's only slower than reading everything once, in order.

The crossover usually sits somewhere between 5 and 20 percent, depending on row width and storage. Below it the index wins, and above it the scan does. This is why an index on a boolean column is almost always useless. If the two values are split evenly over a million rows, each value matches half a million rows, and no access path helps.

Where the index stops helping
The sequential scan reads every page once, so its cost stays flat however many rows match. The index scan pays one random read for every matching row, so its cost climbs with the share matched. The two lines cross in the shaded band between 5 and 20 percent. At 40 percent, the index scan costs far more than the sequential scan. The shape is assumed, not measured, and the crossover moves with row width, storage and caching.The sequential scan reads every page once, so its cost stays flat however many rows match. The index scan pays one random read for every matching row, so its cost climbs with the share matched. The two lines cross in the shaded band between 5 and 20 percent. At 40 percent, the index scan costs far more than the sequential scan. The shape is assumed, not measured, and the crossover moves with row width, storage and caching.
Past a small share of the table, the full scan is cheaper. The sequential scan reads every page once, so its cost stays flat however many rows match. The index scan pays one random read for every matching row, so its cost climbs with the share matched. The two lines cross in the shaded band between 5 and 20 percent. At 40 percent, the index scan costs far more than the sequential scan. The shape is assumed, not measured, and the crossover moves with row width, storage and caching.

The rule that follows: index the columns that narrow, not the columns that appear. A column is worth indexing when a typical predicate on it leaves you with a small fraction of the table.

Composite indexes, and why column order is the whole design

A composite index is one index on several columns. An index on (a, b, c) is sorted by a first. Entries with equal a are sorted by b, and entries with equal a and b are sorted by c. This order decides which queries the index can serve. The rule is the leftmost prefix: the index can serve a query that constrains a leading run of its columns, such as a, or a and b. It can't serve a query on b alone, because b is only in order inside each value of a.

So the columns go in this order:

  1. Equality predicates first, such as status = 'open', in any order among themselves.
  2. Then the one range predicate, such as created_at > ?, if there is one.
  3. Then columns you only need to read, not to filter on.

The reason is that once a column is read as a range, the columns after it are no longer in an order you can use. An index on (status, created_at) serves WHERE status = 'open' AND created_at > ? well: it jumps to the open entries and reads their dates in order from there. The same columns as (created_at, status) serve it badly. The range on created_at comes first, so the open entries are scattered through the matched range. The index has to read every entry in the range and check its status.

The same two columns in two orders
Both indexes answer status = 'open' AND created_at > '2026-10-01'. On the left, the index is sorted by status first, so the three matching entries sit next to each other, in green, and the index reads only those. On the right, it is sorted by date first. It seeks to 1 October and reads every entry from there, and throws away the closed ones, in red. With more closed orders in the range, the right side reads more and more entries it does not need.Both indexes answer status = 'open' AND created_at > '2026-10-01'. On the left, the index is sorted by status first, so the three matching entries sit next to each other, in green, and the index reads only those. On the right, it is sorted by date first. It seeks to 1 October and reads every entry from there, and throws away the closed ones, in red. With more closed orders in the range, the right side reads more and more entries it does not need.
With equality first, the matching entries sit together. Both indexes answer status = 'open' AND created_at > '2026-10-01'. On the left, the index is sorted by status first, so the three matching entries sit next to each other, in green, and the index reads only those. On the right, it is sorted by date first. It seeks to 1 October and reads every entry from there, and throws away the closed ones, in red. With more closed orders in the range, the right side reads more and more entries it does not need.

One good composite index usually replaces three single-column ones, and it costs a third as much on every write. Most of the real gains come from this kind of merging, not from adding more indexes.

Covering indexes, and the second read you can delete

If the index already holds every column the query touches, the database can answer without going to the table at all. That is an index-only scan. It removes the random read into the table, which is usually the expensive half.

The cost is size. Each column you add makes the index entries wider, so fewer of them fit in a page. The tree gets deeper, and less of it fits in memory. Postgres and SQL Server let you attach columns with INCLUDE, as payload rather than as sort keys. Payload columns are stored only in the leaves, so they stay out of the sort order, out of the comparisons and out of the upper levels of the tree.

Cover a query that runs constantly and reads two or three narrow columns. Don't cover one that reads eight, because then you've built a second copy of the table.

Sargability: predicates that cannot use an index

An index is sorted by the value stored in the column. If you wrap the column in a function or an expression, the value being compared is no longer the value the index is sorted by. So the database can't seek the index, which means it can't jump straight to the matching entries. A predicate that can use an index is called sargable, short for "search argument able".

this cannot use an index on colwrite this instead
WHERE YEAR(created_at) = 2026WHERE created_at >= '2026-01-01' AND created_at < '2027-01-01'
WHERE LOWER(email) = ?index on LOWER(email), or store it normalised
WHERE amount * 100 > ?WHERE amount > ? / 100
WHERE name LIKE '%smith'nothing; a leading wildcard is unindexable by a B-tree
WHERE col::text = ?fix the type so no cast is needed
WHERE col + 0 = ?remove the arithmetic

The rule is one line: keep the indexed column bare on one side of the comparison. Every row of the table above breaks that rule, except the leading wildcard.

The leading wildcard has no workaround with a B-tree. The index is sorted from the first character, and '%smith' says nothing about the first character, so the sort order can't help. It needs a different index type. That is usually a trigram index, which indexes every three-letter piece of the text, or an inverted index, which maps each word to the rows that contain it. Both belong to full-text search.

Statistics, and why the planner guesses wrong

The planner doesn't know how many rows match your predicate. It estimates the number from statistics, which it builds by sampling the table: how many distinct values a column has, which values are most common, and how the values are spread out.

Three things break those estimates, and each one leads to a particular wrong plan.

Stale statistics. You bulk-load 10 million rows, and the statistics still describe a table of 1,000 rows. The planner picks a nested loop join, which is right for 1,000 rows and a disaster for 10 million.

Correlated columns. The planner assumes columns are independent of each other. Given WHERE city = 'Mumbai' AND country = 'India', it multiplies the two selectivities together. That estimate is far too low, because every Mumbai row is also an India row, so the columns aren't independent at all. Postgres, SQL Server and Oracle can keep statistics on a group of columns for exactly this case.

Skewed values. Take a column where one value covers 90 percent of rows and the rest are unique. The average tells you nothing about either kind of value, and a plan chosen for the average is wrong for both. This is the same skew problem that comes up elsewhere in the course.

The method

There are seven steps. Steps two and three find most answers, and neither one needs you to change anything.

1. Get the actual plan, not the estimate. EXPLAIN prints the plan the database intends to use, with the planner's guesses. EXPLAIN ANALYZE runs the query and prints what really happened. Only the second one is evidence.

2. Find the node that is actually expensive. A plan is a tree of steps, and each step is a node. The time shown at a node usually includes the time of everything below it, so the top node shows the total and tells you nothing. Look for the node whose own time is large. It's often deep in the tree and looks small.

3. Compare estimated rows against actual rows at that node. This is the most useful number in the plan. If the two are within a small factor, the planner understands your data. If they're a hundred times apart or more, it doesn't, and your problem is statistics rather than indexing. Refresh the statistics before you do anything else.

4. Decide which access path you want. Pick it from the table above, and say it out loud: "this should be an index scan returning about 200 rows."

5. Check the predicate can use an index. The indexed column has to be bare on one side of the comparison. This costs nothing to check, and it's a common cause.

6. Design the index. Put the equality columns first, then the range column, then the covered columns. Check whether you can extend an existing index instead of adding a new one.

7. Verify, and price the write. Run the plan again to confirm the path changed. Then count the indexes on that table, and ask what you've just added to every insert.

Worked examples

There are four. Each one ends in a decision, and each one fails in a different way.

The index exists and the query ignores it

A dashboard filters orders by year:

SELECT * FROM orders WHERE YEAR(created_at) = 2026 AND status = 'shipped';

There is an index on created_at. The plan shows a sequential scan.

Nothing is wrong with the index. The predicate wraps created_at in a function, so the values the index is sorted by aren't the values being compared. To use the index, the database would first have to compute YEAR(created_at) for every entry, and then the sorted order gives it nothing to seek on.

SELECT * FROM orders
WHERE status = 'shipped'
  AND created_at >= '2026-01-01' AND created_at < '2027-01-01';

Decision: rewrite the predicate, and add no index. The failure was sargability. The tell was an index that exists, looks correct, and never appears in a plan.

The index is used and the column order is wrong

It's the same table, with an index on (created_at, status) this time, and the same query. The plan uses the index and is still slow.

The range on created_at comes first, so the index seeks to the start of 2026 and then walks every entry in that year. The status values are scattered through that range, so the index checks status on each entry instead of seeking on it. Say a year holds 2,000,000 orders and 4,000 of them are shipped. The index visits 2,000,000 entries to return 4,000.

If you reverse it to (status, created_at), the index seeks straight to the shipped orders and then walks one unbroken range of dates within them.

Index entries read to return 4,000 orders
Both indexes return the same 4,000 shipped orders from 2026. With the range first, the index reads all 2,000,000 entries for the year and keeps one in 500, in red. With equality first, it reads only the 4,000 it returns, in green, a hairline on this scale.Both indexes return the same 4,000 shipped orders from 2026. With the range first, the index reads all 2,000,000 entries for the year and keeps one in 500, in red. With equality first, it reads only the 4,000 it returns, in green, a hairline on this scale.
The wrong column order reads 500 times more entries. Both indexes return the same 4,000 shipped orders from 2026. With the range first, the index reads all 2,000,000 entries for the year and keeps one in 500, in red. With equality first, it reads only the 4,000 it returns, in green, a hairline on this scale.

Decision: reorder the columns, equality first and range second. The plan looked healthy, and the row counts gave it away.

The planner picks the wrong plan and both options exist

A join between users and events was fast for months and is suddenly slow. Nothing was deployed. The plan changed from a hash join to a nested loop.

The plan shows the estimate for events at 1,200 rows and the actual at 4.1 million. A nested loop is the right choice for 1,200 rows and a disaster for 4.1 million. A bulk import ran and nobody refreshed the statistics. So the planner is costing a table it thinks is more than three thousand times smaller than it is.

Estimated and actual rows from events
The planner's estimate, in grey, is a sliver next to the actual row count, in red. The nested loop it chose looks up the other table once per row. That is cheap at 1,200 rows and runs 4.1 million lookups at the real size.The planner's estimate, in grey, is a sliver next to the actual row count, in red. The nested loop it chose looks up the other table once per row. That is cheap at 1,200 rows and runs 4.1 million lookups at the real size.
The planner chose a plan for 1,200 rows and got 4.1 million. The planner's estimate, in grey, is a sliver next to the actual row count, in red. The nested loop it chose looks up the other table once per row. That is cheap at 1,200 rows and runs 4.1 million lookups at the real size.

Decision: refresh the statistics. Add no index and change no query. Then add a step that refreshes statistics after every bulk load, because this will happen again.

This is the failure mode to learn: the query, the schema and the indexes were all unchanged and correct, and the plan was wrong anyway. Step 3 of the method finds it in seconds, and no amount of index design would have.

The reads are fine and the writes are dying

An events table takes 8,000 inserts a second. Over two years it has collected eleven indexes, each one added to fix one slow dashboard query.

Every insert now does twelve writes. Write latency has crept up from 2 ms to 30 ms. No single change caused it, and every index can be justified on its own.

You check which indexes are used. Four show zero scans since the usage counters were last reset. Three more overlap: (a), (a, b) and (a, b, c) all exist, and by the leftmost prefix rule the third one serves the queries of all three.

Writes per second on the events table
Each insert writes the row once, in orange, and one entry into every index, in purple. With eleven indexes, 8,000 inserts a second become 96,000 writes a second, and the rows are only 8,000 of them. With five indexes, the same inserts make 48,000 writes a second.Each insert writes the row once, in orange, and one entry into every index, in purple. With eleven indexes, 8,000 inserts a second become 96,000 writes a second, and the rows are only 8,000 of them. With five indexes, the same inserts make 48,000 writes a second.
Eleven indexes turn 8,000 inserts a second into 96,000 writes. Each insert writes the row once, in orange, and one entry into every index, in purple. With eleven indexes, 8,000 inserts a second become 96,000 writes a second, and the rows are only 8,000 of them. With five indexes, the same inserts make 48,000 writes a second.

Decision: drop the four unused indexes, drop (a) and (a, b), and keep (a, b, c). Eleven indexes become five. Indexes get added one at a time, by different people solving different problems, and nobody is assigned to the total.

Where it goes wrong

1. Adding an index before reading the plan

This is the reflex, and it fixes only one of the three possible failures. If the cause was sargability or statistics, the new index does nothing except slow down every write. It also stays there for good, because nobody checks whether it's used.

2. One index per column

Three single-column indexes on a, b and c do far less for a query on all three columns than one index on (a, b, c). They also cost three times as much on write. A database can combine single-column indexes with a bitmap. That is better than nothing and much worse than the right composite index.

3. Getting composite column order backwards

This means putting the range column before the equality columns. The index is used, the plan looks reasonable, and the index reads far more entries than it returns. The tell is a large gap between rows read and rows returned at the index node.

4. Indexing a low-cardinality column

A low-cardinality column has only a few distinct values. Think of a boolean, or a status with three values where one status covers most rows. The index exists and the planner correctly ignores it for the common value, because reading 60 percent of the rows in random order is worse than reading all of them in order.

5. Trusting EXPLAIN without ANALYZE

The estimate is what the planner believes. When the problem is that its beliefs are wrong, reading them back confirms nothing. Always get the actual rows and the actual time.

6. Never removing anything

People add indexes to fix a problem, and nobody removes them, because removing one feels risky and nobody sees the benefit. Most engines record how often each index is used. Check it once a quarter and delete what has never been scanned.

7. Forgetting that an index is also a cache tenant

Every index competes with the tables and the other indexes for space in the buffer pool. An index only helps if the pages it needs are in memory. A large new index doesn't just cost writes. It also pushes other pages out of the buffer pool, so it can make unrelated queries slower. People rarely blame the index for this, because the slowdown shows up in a different query.

8. Treating a sequential scan as a bug

A sequential scan is the right plan for a query that wants a large fraction of the table. If you chase every scan out of every plan, you end up with eleven indexes, like the events table above.

If you memorise nothing else

the linewhy it holds
An index is a second sorted copy, paid for on every writefive indexes means six writes per insert
It makes one access path cheap, not queries fastthree things must go right and they fail independently
Estimated against actual rows is the most useful number in a plana large gap means statistics, not indexing
A B-tree is 3 to 4 levels deep at any realistic size100x more rows costs one extra page read
Leaves are linked, so ranges and ORDER BY come freethis is why B-tree beats hash for almost everything
Keep the indexed column bare on one sidea function on the column makes the index unusable
Equality columns first, then the range columnthe first range ends the useful part of the index
One composite usually replaces three single-column indexesat a third of the write cost
A sequential scan is often the correct planabove roughly 5 to 20 percent selectivity it wins
Low-cardinality columns do not benefita boolean over a million rows helps nobody
An index-only scan removes the second, random readcover narrow hot queries, not wide ones
Correlated columns fool the plannerit assumes independence and multiplies selectivities
Indexes evict other pages from memorythe cost shows up in a query you were not looking at
Nobody is assigned to the total number of indexesso audit usage and delete, on a schedule

What is expected at each level

Mid-level

Knows an index speeds up lookups and can name the B-tree. Reaches for EXPLAIN when prompted and reads the plan from the top down. Adds a single-column index for each slow query, and doesn't mention the write cost or check whether an existing index could be extended. Usually treats a sequential scan as a problem to remove.

Senior

Reads EXPLAIN ANALYZE and looks at actual rows rather than estimates. Designs composite indexes with equality before range, and can say why the order matters. Spots a predicate that can't use an index and rewrites it rather than indexing around it. Prices the extra writes each index adds, and knows a scan can be the right plan.

Staff+

Checks estimated against actual rows first, and treats a large gap as a statistics problem rather than a missing index. No index fixes that failure. Knows correlated columns break the planner's assumption that columns are independent, and reaches for extended statistics. Merges overlapping indexes using the leftmost prefix rule instead of adding more, and audits usage on a schedule because nobody owns the total. Accounts for each index taking space in the buffer pool, so its cost can land on a query nobody was measuring.

Sources

The structural facts here are worked out rather than measured, and the working is in the article so you can check it.

  • PostgreSQL's documentation on index types, EXPLAIN, and planner statistics. Source for the access path names, for how EXPLAIN ANALYZE differs from plain EXPLAIN, for INCLUDE columns, and for extended statistics on correlated columns. Behaviour differs between engines, so check your own.
  • Markus Winand's Use The Index, Luke and SQL Performance Explained. These are the standard reference for the leftmost prefix rule and for sargability, and for the argument that column order is the design rather than a detail.
  • The B-tree depth arithmetic uses an 8 KB page and a 22 byte entry, both stated in the worksheet. Real fanout, the number of entries per page, varies with key width and fill factor. So treat the depth of 3 to 4 as an order-of-magnitude result rather than a measurement. Its conclusion holds across any plausible variation of those inputs: lookup cost is nearly flat in table size.
  • The 5 to 20 percent selectivity crossover is a rule of thumb rather than a constant. It moves with row width, storage type and how much of the table is cached, and the only reliable version is the one you measure on your own data.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.