Databases and storage

Indexes and B-trees

How a B-tree finds one row among 100 million in three or four page reads, how to design composite and covering indexes, and what every index costs on writes.

Lesson13 min read
Video walkthrough: not recorded yet. The lesson below is complete without it.

The problem

An orders table has 100 million rows of about 200 bytes each, so about 20 GB. The application runs this several hundred times a second:

SELECT * FROM orders WHERE customer_id = 4207;

With no index the database has one option: read every row and keep the ones that match. Even on a fast NVMe drive reading 1 to 2 GB per second, that is 10 to 20 seconds per query, to return perhaps 30 rows.

The first idea is to keep the data sorted by customer_id and use binary search. That needs about 27 probes for 100 million rows, and each probe lands on a different part of the disk. Worse, a sorted file is expensive to change: inserting one row in the middle means shifting everything after it. A hash table gives fast equality lookups, but it cannot answer “between”, “greater than” or “in sorted order”.

Around 1970 Rudolf Bayer and Edward McCreight, working at Boeing, designed a structure for exactly this problem: sorted data on a disk that is read and written one block at a time. They called it the B-tree, and it is still the default index in almost every relational database.

How a B-tree works

Disks and operating systems work in fixed-size blocks, so databases store data in pages: 8 kB by default in PostgreSQL and 16 kB in MySQL’s InnoDB. A B-tree is a tree in which every node is one page.

  • An internal page holds sorted keys with a pointer to a child page between each pair of keys.
  • A leaf page holds the index entries: a key and the location of its row.
  • Every leaf is at the same depth, so every lookup costs the same number of page reads.

Most databases use the B+tree variant. Values live only in the leaves, and each leaf links to its neighbours. Internal pages then hold nothing but keys and pointers, so more of them fit, and a range scan can walk along the leaves without going back up.

Finding one row through a B-tree index9 components: Query, Root page, Internal page, Internal page, Internal page, Leaf page, Leaf page, Leaf page, Table rows. Connections: Query to Root page; Root page to Internal page; Root page to Internal page; Root page to Internal page; Internal page to Leaf page; Internal page to Leaf page; Internal page to Leaf page; Leaf page and Leaf page; Leaf page and Leaf page; Leaf page to Table rows (row location).Querycustomer_id = 4207Root pagekeys 1000 and 5000Internal pagekeys below 1000Internal pagekeys 1000 to 4999Internal pagekeys 5000 and upLeaf pagekeys 4000 to 4199Leaf pagekeys 4200 to 4399Leaf pagekeys 4400 to 4599Table rows100 million rows, 20 GB2.5 million pagesrow location

Step 1 of 8

The orders table holds 100 million rows in about 20 GB. Without an index, finding the orders of customer 4207 means reading all 2.5 million pages of the table, even though only a handful of rows match.

Read the steps as text
  1. The orders table holds 100 million rows in about 20 GB. Without an index, finding the orders of customer 4207 means reading all 2.5 million pages of the table, even though only a handful of rows match.
  2. An index on customer_id is a tree of pages. The search starts at the root page, which holds sorted keys and one pointer per key range. The picture shows three children per page. A real page holds a few hundred.
  3. 4207 falls between 1000 and 5000, so the engine follows the middle pointer to an internal page. One page read has ruled out most of the table.
  4. The internal page narrows the range again and points at one leaf page. Root and internal pages are few and small, so in practice they are already in memory.
  5. The leaf page holds the index entries themselves, in sorted order. Each entry is a key and the location of its row. A binary search inside the page finds the entries for 4207.
  6. One more read fetches the row from the table. The whole lookup cost three index pages and one table page, instead of 2.5 million pages. A covering index would skip this last step.
  7. A range query uses the same path once. To find customers 4207 to 4450, the engine descends to the first leaf and then walks sideways along the links between leaves, with no need to climb back up the tree.
  8. Because each page fans out to hundreds of children, three levels are enough to index about 100 million rows and four levels cover tens of billions. That is why a lookup stays fast as the table grows.
Finding one row through a B-tree index

Fan-out and height, with numbers

An entry in an internal page is a key and a child pointer, a few tens of bytes for an integer key. So a page holds a few hundred entries. Take 500 as a round figure for 100 million rows:

Level Pages Size at 8 kB
Root 1 8 kB
Internal 400 3.2 MB
Leaf 200,000 1.6 GB

Three levels are enough, and a fourth would cover over 60 billion rows. The root and internal levels total a few megabytes, so they stay in memory. A lookup usually needs one disk read for the leaf and one more for the row.

Inserts keep the tree balanced. The database finds the right leaf and adds the entry in sorted position. If the leaf is full, it splits into two half-full pages and a new key goes into the parent, which may split in turn. The tree grows taller only when the root splits. One consequence is that pages are never all full: with inserts in random key order they average roughly 70% full.

B-tree vs LSM tree

Open full screen

B-tree: update pages in place

empty

Each box is a disk page holding up to 3 keys. Pages on the last search path are outlined in blue.

Height
1
Pages written, last insert
0
Pages written, total
0

LSM tree: append, then merge later

Memtable (in memory, up to 4 keys)

empty

Level 0 (sorted files on disk)

no files
Log appends
0
Flushes
0
Compactions
0
Write amplification
0.0x

Insert random keys and compare. The B-tree pays on every write: it finds the right page and rewrites it where it lives, and sometimes splits. The LSM tree makes each write a cheap append, then pays later, in bulk, when it flushes and compacts. Write amplification is how many times each key has been written to disk so far.

What just happened

Nothing yet. Use the controls above.

    Insert a few dozen keys and watch the B-tree side: each key goes to one leaf, and a full leaf splits and pushes a key up to its parent. The LSM side is the subject of the next lesson.

    Clustered and secondary indexes

    Where the row itself lives differs between databases, and it changes how you design keys.

    • InnoDB (MySQL) stores the table inside the primary key’s B+tree. This is a clustered index: the leaf pages hold the full rows, in primary key order. A secondary index stores the indexed columns plus the primary key value, so a lookup through a secondary index walks two trees.
    • PostgreSQL stores rows in an unordered heap. Every index, including the primary key, is a secondary index whose entries point to a row’s physical location.

    Two practical results follow. In InnoDB the primary key is copied into every secondary index entry, so a long key bloats all of them, and a random key such as a UUIDv4 scatters inserts across the clustered index and causes page splits. Time-ordered ids avoid this (see unique ids). In PostgreSQL an update writes a new version of the row, and unless that version fits on the same page and no indexed column changed, every index needs a new entry.

    Composite and covering indexes

    A composite index on (a, b, c) is sorted by a, then by b within equal a, then by c. Think of a phone book sorted by surname and then first name: it is useful if you know the surname, and close to useless if you know only the first name. This is the leftmost prefix rule. The index serves conditions on a, on a and b, or on all three, but not on b alone.

    The rule for column order:

    1. Columns compared with = go first.
    2. Then the column used for a range or for ORDER BY.
    3. A column after a range condition cannot narrow the scan any further.

    For this query:

    SELECT id, total FROM orders
    WHERE customer_id = 4207 AND status = 'paid'
    ORDER BY created_at DESC LIMIT 20;

    the index (customer_id, status, created_at) lets the database jump to the right customer and status and read 20 entries that are already in date order. No sort is needed.

    A covering index contains every column the query needs, so the database never visits the table. PostgreSQL calls this an index-only scan, and since version 11 you can add payload columns with INCLUDE (total) without making them part of the sort key. In MySQL, EXPLAIN shows “Using index”. On a hot query that returns many rows this removes most of the page reads, because each row would otherwise need its own visit to the table. (PostgreSQL still visits the table for pages that changed recently.)

    The write cost

    Indexes are not free. Each one is a separate tree that has to be kept in step with the table.

    • An insert adds an entry to every index. With five indexes that is the row plus five tree insertions, each landing on an effectively random leaf page.
    • An update that changes an indexed column removes one entry and adds another.
    • Every change is also written to the write-ahead log, and index pages compete with table pages for memory.

    So an index trades slower writes and more storage for faster reads. A table with ten indexes “to be safe” pays that cost on every write for queries that may never run. LSM trees are a different answer to the same write cost.

    When an index is not used

    The query planner estimates costs and picks the cheapest plan. It will ignore your index when:

    • Too many rows match. If a condition matches a large share of the table, reading the table in order is cheaper than jumping around it. An index on a boolean or a status column with three values rarely helps on its own.
    • The column is wrapped in a function or cast, as in WHERE lower(email) = ... or a comparison between a string column and a number. Index the expression instead.
    • The pattern starts with a wildcard, as in LIKE '%son'.
    • The leading column is missing from the conditions.
    • Statistics are stale, so the row estimates are wrong.

    Run EXPLAIN to see the plan instead of guessing, or EXPLAIN ANALYZE to run the query and see real row counts and timings.

    When to choose it and when not to

    Add an index when a frequent query filters, joins or sorts on a column and returns a small share of the table. Design it for that query, with the columns in the order the rule gives.

    Do not add one when the table is small, when the column has few distinct values, when the query runs once a day in a batch job, or when the table takes heavy writes and the query is rare. Check for unused indexes and drop them.

    In the interview

    Indexes come up as soon as you write a data model. After listing the tables, say which queries are hot and which index serves each. Mentioning one unprompted composite index with a reason is a strong signal.

    A good answer takes about a minute: “The feed query filters by user_id and sorts by created_at, so I would index (user_id, created_at). That is a B-tree, three or four levels deep, so a lookup is a few page reads. I would make it covering if the query reads only a couple of columns. I would not index every column, because each index adds a tree update to every write.” Then, if asked why a query is still slow, reach for EXPLAIN, selectivity and the leftmost prefix rule.

    Key takeaways

    • A B-tree page points to hundreds of children, so three or four levels index billions of rows and a lookup is a few page reads.
    • In a B+tree the values sit only in the leaves, and the leaves are linked, which makes range scans and sorted reads cheap.
    • InnoDB stores the table inside the primary key index and secondary indexes point to the primary key. PostgreSQL stores rows in a heap and every index points to a row location.
    • In a composite index, order the columns as equality filters first, then the range or sort column. The index serves only leftmost prefixes.
    • A covering index answers a query from the index alone and skips the trip to the table.
    • Every index is another tree to update on each write. Add indexes for queries you can name, and remove the ones nothing uses.

    Try it

    Check yourself

    1. Assume each B-tree page holds about 500 entries. How many levels does an index on 100 million rows need, and why?
    2. A table has an index on (country, city, created_at). Which query gets the least help from it?
    3. A query filters with lower(email) = 'sam@example.com' and the table has a plain index on email. The planner scans the whole table. Why?
    4. In MySQL InnoDB, why does a long random primary key make every secondary index more expensive?
    5. A write-heavy table has four indexes and a team adds a fifth. Which effect is most certain?

    0 of 5 answered

    Flashcards

    These 6 cards are in your review deck. Tap a card to see the answer.

    Why is a B-tree lookup so shallow?

    Each page holds hundreds of keys and child pointers. With a fan-out of about 500, three levels reach 125 million rows and four levels reach over 60 billion.

    What is the difference between a B-tree and a B+tree?

    A B+tree keeps values only in leaf pages and links the leaves together. Internal pages hold only keys, so fan-out is higher, and range scans walk along the leaves.

    Clustered index versus secondary index?

    A clustered index stores the rows themselves in key order, so there is one per table. A secondary index stores keys plus a pointer to the row, which costs a second lookup.

    What is the leftmost prefix rule?

    An index on (a, b, c) can serve conditions on a, on a and b, or on all three, but not on b or c alone. Put equality columns first and the range or sort column last.

    What is a covering index?

    An index that contains every column a query needs, so the database answers from the index without visiting the table. PostgreSQL calls the result an index-only scan.

    Name three reasons the planner ignores an index.

    The condition matches a large share of the table, the column is wrapped in a function or cast, or the query does not use the leading column of a composite index. A leading wildcard in LIKE is a fourth.

    Review the deck