What Is a B-tree Index - and When an Index Makes Things Worse

A B-tree index is a sorted, balanced tree stored on disk that lets a database find a row by key in a handful of page reads instead of scanning the whole table. When someone says "add an index" without qualifying it, they almost always mean a B-tree index - it is the default index type in essentially every relational database.

The problem it exists to solve is a physical one. Table rows live wherever the storage engine put them, in no useful order. Without something else to consult, answering WHERE email = ? means reading every page of the table and discarding almost all of it.

An index is a second structure that keeps the keys in sorted order and points back at the rows. Sorted order is what makes binary search possible, and the tree shape is what keeps that search cheap when the data lives on a device where every read costs you a round trip.

The catch is that you now have two structures to keep consistent on every write. That trade is the whole story, and it is why "just add an index" is sometimes the wrong answer. Detailed image of illuminated server racks showcasing modern technology infrastructure.

ConceptB-tree index (specifically the B+tree variant in most databases)
Where it sitsStorage layer - sits inside the database engine, between the query planner and the pages on disk
In one sentenceA balanced, sorted tree of fixed-size pages that turns a key lookup or range scan into a few page reads, at the cost of extra work on every insert, update and delete.

The 60-Second Answer

A B-tree index keeps a copy of one or more columns in sorted order, organised as a shallow tree of fixed-size pages, with pointers down to the actual rows.

The one problem it solves: finding rows by key, or reading a range of keys in order, without touching the rest of the table. Lookup cost grows with the depth of the tree, not the size of the table, and the tree stays shallow even for very large tables.

The one cost it adds: every insert, update to an indexed column, and delete must also modify the index. That is extra I/O, extra lock contention on hot key ranges, and extra storage you have to keep in cache to get the benefit.

The decision rule: index the columns your selective lookups and ordered scans actually filter on. Do not index a column whose values barely narrow anything down.

How It Actually Works

1. The index is a separate sorted copy of the key columns

Keys plus a pointer, not the whole row

The index stores the indexed column values, sorted, each paired with a pointer to the row - either a physical location or the primary key, depending on the engine. The table itself stays unordered.

This is why an index on (email) can answer WHERE email = ? quickly but tells the engine nothing about WHERE phone = ?. The sort order is the entire source of the speedup, and a structure sorted by email is arbitrary with respect to phone.

-- index knows email order, so it can seek
SELECT id FROM users WHERE email = 'a@example.com';

-- index on (email) is useless here; different column
SELECT id FROM users WHERE phone = '555-0100';

⚠️ In production — People forget the index is a copy. On a wide table with several indexes, your index data can rival or exceed the size of the table, and all of it competes for the same buffer cache. Adding an index can evict the pages a different query depended on, and you see that as an unrelated query getting slower.


2. Everything is organised into fixed-size pages because disks read pages

The page is the unit of I/O

The database does not read individual keys. It reads a page - a fixed-size block, the same unit it uses for table data. Every node in the B-tree is exactly one page.

This is the design constraint that produces the whole shape. If reading one byte costs the same as reading a few kilobytes, you want each read to deliver as many keys as possible. So each node packs in hundreds of keys rather than the two children a binary tree would give you.

⚠️ In production — Page-sized nodes mean a row that is a few bytes smaller or larger can change how many keys fit per page, which changes the fanout, which changes tree depth. This is why long text primary keys hurt: fewer keys per page, taller tree, more reads per lookup. It rarely shows up in a dev database small enough to sit entirely in memory.


3. High fanout keeps the tree shallow, and depth is what you pay

Hundreds of children per node, not two

Because each node holds many keys, each node has many children. A tree only a few levels deep can therefore address an enormous number of rows. Lookup cost is the number of levels you descend, so it grows roughly with the logarithm of the row count - and with a large base.

The practical consequence: going from a large table to a much larger table typically adds a level or two, not a proportional amount of work. That is the property you are buying.

⚠️ In production — The top levels of the tree are read by every single lookup, so they stay hot in cache and effectively cost nothing. Only the lower levels actually hit storage. This is why measured lookup latency is usually better than a naive count of levels suggests - and why a cold cache after a restart makes the same query look dramatically slower for a while.


4. Internal nodes route; leaf nodes hold the payload

Signposts above, data below

In the B+tree variant that relational databases actually use, internal nodes hold only separator keys and child pointers - they tell you which subtree to descend into. All the key-to-row pointers live in the leaf level.

Keeping internal nodes payload-free is what lets them pack in so many separator keys, which is what maximises fanout. Every lookup descends to a leaf; there are no early exits partway down.

⚠️ In production — Because every lookup goes all the way to a leaf, a key that does not exist costs about the same as one that does. Checking existence is not free, and a loop that probes thousands of missing keys one at a time is just as expensive as one that finds them - a pattern that quietly dominates some batch jobs.


5. Leaf pages are linked, which is what makes range scans cheap

Descend once, then walk sideways

Leaf pages are chained to their neighbours in key order. To read a range, the engine descends the tree once to find the start of the range, then walks the leaf chain forward, reading each page in order.

This is the capability people underrate. BETWEEN, >, ORDER BY on the indexed column, LIMIT on a sorted result - all of these ride the leaf chain and stop as soon as they have enough rows. The index is not just a point-lookup structure; it is an ordering you can borrow.

-- descends once, then walks leaves and stops at 20 rows
SELECT * FROM events
WHERE created_at >= '2026-01-01'
ORDER BY created_at
LIMIT 20;

⚠️ In production — The walk is cheap in index order but the row fetches may not be. If the engine has to jump to the heap for each matching row, a wide range scan becomes many scattered reads and the planner may rightly decide a sequential scan is cheaper. A query that uses the index for 100 rows can abandon it for 100,000 - same query, different parameters, completely different plan.


6. Inserts split pages, and splits are how the tree stays balanced

Full page splits in two, parent absorbs the key

A new key goes into the leaf page where it belongs in sort order. If that page is full, the engine splits it: roughly half the keys move to a new page, and a separator key is pushed up into the parent. If the parent is full, it splits too, and in the limit the root splits and the tree grows one level taller.

Growth happens at the root, not the leaves. That is what guarantees every leaf stays the same distance from the root, which is what guarantees uniform lookup cost. There is no degenerate case where one branch becomes a linked list.

⚠️ In production — Insert order matters enormously. Monotonically increasing keys always append to the rightmost leaf, which splits predictably and packs densely. Random keys - UUIDv4 is the classic case - insert all over the key space, dirtying pages everywhere and leaving them half-full. Same number of rows, substantially more I/O and a larger index. If you need UUIDs, use a time-ordered variant so inserts stay local.


7. Deletes and updates leave space behind, and the index has to be maintained

Free space is reused, not reclaimed

Deleting a key frees space inside a leaf page but does not shrink the tree. The page stays allocated and the space is available for future keys in that key range. An update to an indexed column is usually a delete plus an insert in index terms, possibly landing on a different page entirely.

Over time a workload that deletes from one key range and inserts into another leaves pages that are mostly empty but still have to be read. This is index bloat, and it means the same logical row count occupies more pages and more cache than it needs to.

⚠️ In production — Bloat is slow and invisible. Query plans do not change, the index just gets gradually more expensive to traverse, and the only symptom is latency drifting upward over months. Every engine has a way to rebuild an index; knowing which one yours has, and whether it locks writes while doing it, is operational knowledge you want before you need it.


8. Composite indexes are sorted left to right, and that order is a commitment

Leftmost prefix or nothing

An index on (a, b, c) sorts by a, then by b within equal a, then by c. The engine can seek efficiently using a leftmost prefix: a, or a and b, or all three. It cannot seek on b alone, because within the index b values are scattered across every a group.

Column order is therefore a design decision, not a formatting choice. Put equality predicates first and the range or ordering column last, because once you hit a range the remaining columns are no longer in usable order.

-- index on (tenant_id, created_at)
WHERE tenant_id = 7 AND created_at > '2026-01-01'  -- seeks
WHERE created_at > '2026-01-01'                     -- cannot seek

⚠️ In production — Teams end up with (a, b) and (b, a) and (a) on the same table because each was added for one query under pressure. (a) is redundant with (a, b), and every redundant index is pure write-path cost for zero read benefit. Audit the index set as a whole, not query by query.

Close-up of labeled wooden storage drawers, perfect for organization concepts. ## Where You Meet It
  • A multi-tenant SaaS application where every query is scoped by tenant. An index on (tenant_id, created_at) lets a request descend once to the tenant's key range and walk forward for that tenant's recent records, never touching other tenants' data. Without it, each tenant's dashboard scans a table containing every tenant's rows - and the cost grows as other customers sign up.
  • A users table with a unique constraint on email. The uniqueness check itself is a B-tree lookup: before inserting, the engine descends the index to see whether the key is already there. The constraint and the index are the same object, which is why login-by-email is fast as a side effect of the constraint you declared for correctness.
  • A cursor-paginated API over an append-only event log. WHERE (created_at, id) > (?, ?) ORDER BY created_at, id LIMIT 50 descends to the cursor position and reads 50 leaf entries forward. Cost is flat regardless of how deep into the log the client has paged, which is the property OFFSET pagination cannot give you.
  • A foreign key column on a child table. When a parent row is deleted or updated, the engine must find referencing children. With no index on the child's foreign key column, that check scans the child table on every parent write - a common cause of deletes that are inexplicably slow on a table nobody thought was involved.
  • A background job that processes rows by status. An index on (status, id) restricted to the pending values lets the worker pull the next batch by seeking to the pending range directly, instead of scanning a large table where almost everything is already done.

When You Actually Need It

  • A query filters on a column and matches a small fraction of the table - the planner reports a sequential scan and the row count returned is far smaller than the rows examined.
  • You read ranges or need sorted output on a specific column: BETWEEN, >, ORDER BY ... LIMIT, or cursor pagination. The leaf chain gives you the ordering for free and lets the query stop early.
  • The column backs a uniqueness or foreign key constraint. The index is doing correctness work, not just performance work, and the engine needs the lookup on every write anyway.
  • The table is large enough that it no longer fits comfortably in cache, so a full scan means real storage I/O rather than a fast in-memory pass.
  • A small number of known query shapes dominate your traffic, and a composite index on their leftmost predicates can serve several of them. Indexes pay best when the access pattern is stable and predictable.
  • The table is read-heavy relative to writes, so the per-write maintenance cost is amortised across many cheap reads.

When You Don't

  • The table is small and stays small. A few thousand rows that fit in one cache's worth of pages are faster to scan in memory than to traverse an index and then fetch rows. The planner often ignores the index you added, correctly. Do nothing; let the scan happen.
  • The column is not selective. An index on a boolean, or on a status column where one value covers most rows, will not be used for the common value - the engine would read most of the index and then most of the table. If you only ever query the rare value, use a partial or filtered index covering just that subset so the index stays tiny; otherwise skip it.
  • The workload is write-dominated and the column is rarely filtered on. High-volume ingest paths pay the index maintenance cost on every row and collect nothing back. Count the actual queries that would use it; if it is one analytics job that runs nightly, let that job scan and keep the write path lean.
  • You need substring or arbitrary-position matching. A B-tree can seek on a prefix because that is a range in sorted order, but LIKE '%term%' has no corresponding range - it will scan regardless. Use full-text search or a trigram-style index built for the purpose.
  • Your predicate is not sorted order at all - geospatial proximity, vector similarity, set containment. These are different problems with different structures. A B-tree on latitude does not find nearby points; use the spatial or vector index type your engine provides.
  • You are adding an index to fix a query you have not read the plan for. Most "we need an index" moments are actually a missing predicate, an unintended cross join, a function wrapping the indexed column so it can no longer seek, or an N+1 in the application. Read the plan first; an index added on a guess is permanent write-path cost for a problem it may not touch. Female student writing circuit diagrams and logic gates in an educational setting on a whiteboard.

What People Get Wrong

"Indexes make queries faster, so more indexes means a faster database."

Each index is a structure that must be updated on every relevant write and that competes for the same buffer cache. Past a handful per table, added indexes typically slow the system overall: writes do more work, cache hit rates fall for everyone, and the planner has more options to get wrong. Indexes make specific access patterns faster, at a cost paid by everything else.

"If I index the column, the query will use the index."

Only if the predicate preserves sorted order and the planner estimates the index as cheaper. Wrapping the column in a function, comparing across incompatible types, or matching too many rows all push it back to a scan. A query filtering on lower(email) cannot use a plain index on email - the index is sorted by the raw values, not the lowered ones.

"A B-tree is the binary tree I learned in a data structures course, just on disk."

The defining property is high fanout, not binary branching, and that exists specifically because the unit of I/O is a page. A binary tree with the same row count would be far deeper and would cost many more reads. The shape is dictated by the storage device, not by the abstract algorithm.

"Index lookups avoid touching the table."

Only when every column the query needs is already in the index - a covering index. Otherwise the engine finds the pointer in the leaf and then fetches the row, which is a second, often scattered, read. This is exactly why a range scan returning many rows can be slower than a sequential scan: the per-row fetches dominate.

Why It Was Built This Way

The B-tree was designed for a device where reading one byte and reading a whole block cost nearly the same, and where the expensive part was getting to the block. Under that constraint, the only metric worth optimising is the number of blocks you touch. Everything about the structure follows: nodes are exactly one page so each read delivers maximum information, fanout is as high as a page allows so the tree is as shallow as possible, and the tree is kept perfectly balanced so no key is ever unusually expensive.

What was traded away is write locality. A hash table would give faster single-key lookups with less structure to maintain. A log that only ever appends would make writes nearly free. The B-tree chose instead to keep data in sorted order at all times, and the price is that an insert must go to a specific page determined by its key - wherever that page happens to live. Random-key insert patterns scatter writes across the whole structure, and page splits turn one logical insert into several physical page modifications. This is precisely the cost that LSM-tree storage engines exist to avoid: they buffer writes sequentially and merge later, accepting more work on reads in exchange.

The reason B-trees remain the default despite that trade is that sorted order is worth more than any single operation. It gives you point lookups, range scans, ordered output, prefix matching, uniqueness enforcement, foreign key checks and cheap cursor pagination from one structure. A hash index gives you equality and nothing else. Once you understand that you are buying an ordering rather than a lookup, the behaviour stops needing memorisation: a B-tree index helps exactly when your query can be expressed as a contiguous range in the index's sort order, and helps you not at all when it cannot.

Related Briefs

What to Read Next

  • covering index vs index-only scan
  • LSM tree vs B-tree storage engine
  • how to read a query execution plan
  • clustered vs non-clustered index

A B-tree index is not a performance setting you turn on; it is a sorted copy of your data that you agree to maintain on every write. It earns that cost when your queries map onto a contiguous range in its sort order and return a small slice of the table. When they do not - small tables, low-selectivity columns, substring search, write-heavy paths nobody queries - the honest answer is to let the scan happen and spend your attention on the query instead.

댓글

이 블로그의 인기 게시물

What Is a Message Queue - and When You Actually Don't Need One

What Is a Bloom Filter - and When You Actually Don't Need One

When to Use GraphQL Over REST API - and When REST Is Still the Right Call