Course contents

04. Database Fundamentals Lesson 3 of 10

Database Indexes

See a full table scan fail as data grows, an index fix it, how a B-tree lookup works, why indexes slow writes, and when an index does not help.

15 minIntermediate8 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Without an index, the database reads every row to find matches; the cost grows with the table.
  • An index is a sorted structure (usually a B-tree) that finds matching rows in a few page reads.
  • Every index must be updated on every write, so indexes speed reads and slow writes.
  • Indexes help selective filters; a filter matching a large share of rows is answered with a scan anyway.
  • Design indexes from real queries: filter columns first, then sort columns, and verify with EXPLAIN.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

A database index is an extra data structure that lets the database find rows by the value of some columns without reading the whole table. Like the index at the back of a book, it maps values (customer 6,042) to locations (these pages). The table stays as it is; the index is a separate, sorted copy of the indexed columns with pointers to the rows, kept up to date on every write.

Why it exists

Without an index, the only way to answer WHERE customer_id = 6042 is to read every row and check it: a full table scan. That is fine for a few thousand rows and hopeless for millions, and it gets worse as the table grows, even though the query and its result don't change. Indexes make lookup cost depend on the depth of a tree (a few page reads) instead of the size of the table.

How it works

B-trees. The default index in PostgreSQL, MySQL (InnoDB), SQL Server and Oracle is a B-tree (strictly a B+tree). Keys are stored in sorted order in fixed-size pages. Leaf pages hold the keys and row pointers (or, in a clustered index, the rows themselves). Above them, branch pages hold key ranges pointing to the pages below, up to a single root. Pages hold hundreds of keys, so three or four levels cover hundreds of millions of rows. A lookup reads one page per level; a range query (BETWEEN, ORDER BY ... LIMIT) finds the start and then walks the leaves in order.

The query planner. The database estimates the cost of each way to run a query (scan, index lookup, index range scan, bitmap scan) from statistics about the data, and picks the cheapest. An index existing doesn't mean it is used; EXPLAIN shows the chosen plan, EXPLAIN ANALYZE runs it and shows real times and row counts.

Selectivity. An index pays off when the filter matches a small fraction of rows. Each match found through the index may mean a random read of a table page; past a few percent of the table, reading the table sequentially is cheaper, and the planner says so.

Composite indexes. An index on (status, created_at) sorts by status, then by date within each status. It serves filters on status, and on status plus a range or sort on created_at, but not filters on created_at alone: the leftmost columns must be used. Put equality filters first, then the range or sort column. If the index also contains every column the query needs (a covering index, INCLUDE in PostgreSQL and SQL Server), the database doesn't touch the table at all.

Other kinds. Hash indexes (equality only), GIN/inverted indexes (full-text, arrays, JSON), GiST and R-trees (geometry, ranges), BRIN (huge append-only tables with naturally ordered columns), and partial indexes (WHERE status = 'pending') that index only the rows a query cares about.

When to use it

  • Columns in WHERE clauses of frequent queries, when the filter is selective.
  • Foreign keys used in joins (many databases don't index them automatically).
  • Columns used in ORDER BY ... LIMIT, combined with the filter columns in a composite index.
  • Uniqueness rules (UNIQUE constraints are enforced with an index).

When not to

  • Low-selectivity columns on their own (booleans, a status with three values) unless combined with other columns or as a partial index.
  • Small tables: a scan of a few pages is as fast as any lookup.
  • Write-heavy tables with rarely-run queries: every index slows every insert; an occasional slow report may be the better deal.
  • Speculatively: indexes "in case someone needs them" cost writes, disk, memory and backup time, and often go unused.

Trade-offs

Choice You gain You pay
Adding an index Selective reads become lookups instead of scans Slower inserts/updates/deletes, disk and memory
Composite index Serves filter + sort in one ordered read Only helps queries using its leftmost columns; larger
Covering index No table access at all for the query Even larger index, more write cost
Many indexes Many query shapes are fast Every write maintains all of them; planner choices get harder
Partial index Small index for exactly the rows queried Only usable by queries with a matching condition

Alternatives

  • Caching results of hot, repeated queries (cache-aside) when the same answers are requested often.
  • Denormalised or precomputed tables (materialised views, summary tables) for expensive aggregates an index can't make cheap.
  • Search engines (Elasticsearch, OpenSearch) for full-text and faceted search across many fields.
  • Partitioning very large tables by time or key, so queries touch only relevant partitions.
  • Rewriting the query so it can use an existing index (avoid functions on indexed columns, leading wildcards, implicit type casts).

Failure modes

  • Missing index discovered in production: a query that was fast on test data scans a table that has grown 1000×. Latency and database CPU climb until connections run out.
  • Index not used: a function on the column (WHERE lower(email) = ...), a type mismatch, a leading % wildcard or stale statistics make the planner ignore it. Check with EXPLAIN.
  • Write slowdown: each new index adds work to every insert; a busy write path can tip into saturation.
  • Index build blocking writes: a plain CREATE INDEX on a large table can lock it for a long time. Use online builds (CREATE INDEX CONCURRENTLY, online DDL).
  • Bloat: heavy updates and deletes leave index pages half empty, making lookups and scans of the index slower until it is rebuilt or vacuumed.

In production

Turn on the slow query log (or pg_stat_statements) and start from the queries that consume the most total time. Look at their plans with EXPLAIN ANALYZE, add indexes for selective filters and sorts, and confirm the plan changed. Build indexes online. Periodically list unused indexes (pg_stat_user_indexes, sys.dm_db_index_usage_stats) and drop them. Keep table statistics up to date so the planner's estimates are right.

Common misconceptions

  • "An index makes every query on that column fast." Only selective ones. A filter matching a large share of rows is cheaper as a scan.
  • "More indexes, more speed." Each index makes writes slower and takes memory; unused ones are pure cost.
  • "Two single-column indexes are as good as one composite index." For filter + sort or multi-column filters, a composite index in the right column order is usually far better.
  • "If the index exists, the database uses it." The planner decides. Check the plan.

Interview angle

When a design has a database, name the access patterns and the indexes that serve them ("orders by customer, newest first: composite index on customer_id, created_at"). Expect follow-ups: how a B-tree lookup works and why it is O(log n), why indexes slow writes, what selectivity means, why a low-cardinality column isn't a good index on its own, the leftmost-prefix rule for composite indexes, and how you'd find a missing index in production (slow query log, EXPLAIN). Mentioning that indexes are the first fix before replicas, caches or sharding shows good judgement.

Model assumptions

This simulation has no query planner, storage pages or real B-trees. Index effects are a cost model: the database's mean read time stands for the cost of the app's main query (120 ms for a full scan of 1M rows, 240 ms for 2M rows, about 4–5 ms for an index lookup) and its mean write time for one insert (5 ms for the row plus about 5 ms per index). The database has 10 connections; a query waiting more than one second for a connection fails. Service times are lognormal (cv 0.3) and arrivals random. The B-tree walk in step 4 is a scripted illustration: the root, branch and leaf pages are scenery, and the packets moving between them are drawn on a fixed schedule, not simulated. Real ratios between scans and lookups depend on caching, row size and hardware, and are often far larger than in this model. Numbers show behaviour and orders of magnitude only.

The lesson as textEvery step of the simulation, written out.
  1. 1. Finding rows without an index

    The order history page runs SELECT * FROM orders WHERE customer_id = ?. The table has a million rows and no index on customer_id, so the database has no way to know where customer 6,042’s orders are. It reads every page of the table and checks every row: a full table scan.

    At 60 queries per second each scan takes about 120 ms. The database copes, but it is busy most of the time and P95 is around 200 ms.

    Scene: The app tier sends 60 queries per second to the Orders database, which has no index and scans the whole table for each read. It copes but is busy most of the time.

    Key idea: Without an index, finding a few rows means reading the whole table.

  2. 2. The table doubles

    Business is good: the table grows to two million rows. A scan reads twice as many pages, so one second in, every query takes about 240 ms.

    Now the database needs more time than it has. Connections stay busy, queries wait, and those that wait over a second fail. Nothing about the query changed; the data did. Scans get slower with every row you add.

    Scene: One second in, the table doubles and each scan takes about 240 ms. The database saturates, queries wait for connections and some fail.

    Key idea: A full scan’s cost grows with the table. A query that was fine at launch can fail a year later.

  3. 3. Create an index

    We run CREATE INDEX ON orders (customer_id). One second in, the index is ready and the same query becomes an index lookup: a few page reads instead of 25,000. In this model it drops from 240 ms to about 4 ms.

    The backlog clears, errors stop and latency falls to little more than the network time. The query text did not change; the database simply found a cheaper way to answer it.

    Scene: One second in, the index on customer_id is ready. Each read drops from about 240 ms to 4 ms; the backlog clears and errors stop.

    Key idea: An index lets the database jump to the matching rows instead of reading everything.

  4. 4. How a B-tree lookup works

    Most database indexes are B-trees: sorted pages arranged in a shallow tree. The root page says which branch holds which key range, each branch says which leaf, and the leaf holds the key with a pointer to the row.

    The animation walks one lookup for customer 6,042: root, then the branch for keys of 5,000 and above, then the leaf for 5,000–7,500, then back with the row’s location, followed by a lookup for customer 1,200 down the other branch. With hundreds of keys per page, three or four levels cover millions of rows, and the top levels usually sit in memory.

    The moving packets here are an illustration, not part of the simulation. The live traffic in the background uses the 4 ms cost from the previous step.

    Scene: An illustration of the index: a root page, two branch pages and four leaf pages. A lookup travels from the database to the root, to a branch, to a leaf and back with the row location: three page reads. Live traffic continues with fast index lookups.

    Key idea: A B-tree finds any key in a handful of page reads, because each level divides the key range by hundreds.

  5. 5. Every index makes writes slower

    A nightly import writes 200 orders per second. Every insert must also add an entry to each index’s B-tree, in the right sorted place.

    One and a half seconds in, the team adds four more indexes (status, created_at, email, total) "just in case". Each insert now updates five trees, its cost triples in this model, and the database goes from lightly loaded to well over half busy. Latency rises with it. Reads did not get any faster for it: no query uses most of those indexes.

    Scene: An import sends 250 queries per second, mostly writes. When four more indexes are added, each write costs three times as much; the database becomes much busier and latency rises.

    Key idea: Indexes speed up reads and slow down every write. Only keep the ones your queries use.

  6. 6. An index that does not help

    The import is over and the four unused indexes are dropped. The main screen now lists orders by status: WHERE status = 'shipped'. There is an index on status, but 40% of all orders are shipped.

    Following the index to 800,000 rows scattered across the table costs more than reading the table in order, so the database scans anyway. The index is ignored, and we are back to 240 ms queries and failures.

    An index helps when it narrows the search to a small fraction of the rows (high selectivity). A column with a handful of values rarely qualifies on its own.

    Scene: The main query now filters by status, which matches 40% of rows. The status index is not worth using, the database scans the table, reads take about 240 ms and some fail.

    Key idea: Indexes help selective filters. A filter matching a large share of rows is cheaper to answer with a scan.

  7. 7. Index the query you actually run

    The screen only shows the 50 newest shipped orders: WHERE status = 'shipped' ORDER BY created_at DESC LIMIT 50. A composite index on (status, created_at) keeps the shipped orders sorted by date, so the database reads the first 50 entries and stops.

    The composite index replaces the status-only one, so writes cost the same. Reads drop to about 5 ms and the errors stop. Design indexes from your queries: the filter columns first, then the sort column.

    Scene: With a composite index on status and created_at, the query reads only the 50 newest shipped orders. Reads take about 5 ms and nothing fails.

    Key idea: A composite index matching filter + sort + limit turns a big scan into a short, ordered read.

  8. 8. Indexes are a trade

    An index is a second, sorted copy of some columns that the database keeps up to date on every write. It turns scans into lookups for selective queries, makes every insert, update and delete do more work, and takes disk and memory.

    Work from real queries: find the slow ones (slow query log, EXPLAIN ANALYZE), index their filter and sort columns, check that the plan actually uses the index, and drop indexes nothing uses.

    Scene: The Orders database has an index on customer_id and a composite index on status and created_at. Reads are fast and nothing fails.

    Key idea: Index for the queries you run, verify with EXPLAIN, and remember each index is paid for on every write.