DEV Community

Cover image for How Database Indexes Work (B-Trees Explained)
Abdeldjalil Chougui
Abdeldjalil Chougui

Posted on Originally published at abdeldjalilchougui.biz

How Database Indexes Work (B-Trees Explained)

You run SELECT * FROM users WHERE email = 'amina@example.com' on a table with ten million rows. Without an index, the database has one option: read every row and check the email. That is a full table scan. With an index on email, it can find the row by reading a handful of pages. The difference between the two can be seconds versus a fraction of a millisecond.

This article explains what an index is, how the B-tree behind most indexes works, and the trade-offs that come with adding one.

The problem: finding rows without reading everything

A table is stored on disk as a set of fixed-size pages (often 8 KB in PostgreSQL, 16 KB in MySQL's InnoDB). Rows are placed in these pages in no useful order for your query. To find all rows where email equals a value, the database must look at every page, because any page might hold a match.

An index is a separate data structure that keeps a copy of one or more columns in sorted order, each entry pointing to where the full row lives. It is the same idea as the index at the back of a book: instead of reading every page to find "transactions", you look the word up in an alphabetical list and jump to page 214.

Why not just a sorted list?

A sorted array lets you binary search: each step halves the search space, so ten million entries need about 24 comparisons. The problem is updates. Inserting a new email in the middle of a sorted array means shifting everything after it. On disk, that is unacceptable.

A balanced binary tree fixes inserts, but each node holds one key, and each step down the tree may mean a separate disk read. Twenty-four random disk reads per lookup is slow.

The B-tree solves both problems.

How a B-tree is built

A B-tree (in databases, almost always the B+tree variant) is a tree where each node is a full disk page and holds many keys, often hundreds.

  • Leaf nodes hold the index entries: the key value and a pointer to the row (in PostgreSQL a tuple ID, in InnoDB secondary indexes the primary key). Leaves are linked to their neighbours, so you can walk them in order.
  • Internal nodes hold separator keys and pointers to child pages. A node with keys [g, p] says: values below g are in the first child, values from g up to p in the second, the rest in the third.
  • The tree is balanced. Every leaf is at the same depth.

Because each node has hundreds of children (a high fan-out), the tree is very shallow. With 300 keys per page, three levels can address 300 × 300 × 300 = 27 million entries. A lookup in a table of tens of millions of rows touches about three or four pages, and the top levels are almost always cached in memory.

A lookup step by step

Say we search for email = 'kamel@example.com':

  1. Read the root page. Its separators are, for example, [d…, m…, t…]. kamel falls between d and m, so follow the second pointer.
  2. Read that internal page. Its separators narrow the range again, say to keys between ka… and ke…. Follow that pointer.
  3. Read the leaf page. Binary search inside the page finds kamel@example.com and its row pointer.
  4. Fetch the row from the table (the heap) using the pointer.

Four page reads instead of scanning the whole table.

Range queries and ordering

Because leaves are sorted and linked, a B-tree also handles ranges well. For WHERE created_at BETWEEN '2026-01-01' AND '2026-01-31', the database descends to the first matching leaf, then walks right along the leaves until it passes the end of the range. The same property lets an index satisfy ORDER BY created_at without a separate sort, and helps MIN and MAX.

Inserts and page splits

When you insert a row, the database also inserts a key into every index on that table. It finds the correct leaf. If there is room, the key is placed in order. If the leaf is full, it splits into two half-full pages and a new separator is pushed into the parent. If the parent is full, it splits too. In rare cases the split reaches the root, a new root is created, and the tree grows one level taller. This is how the tree stays balanced without ever being rebuilt.

In practice

CREATE INDEX idx_users_email ON users (email);

EXPLAIN SELECT * FROM users WHERE email = 'amina@example.com';
-- PostgreSQL shows "Index Scan using idx_users_email" instead of "Seq Scan"
Enter fullscreen mode Exit fullscreen mode

EXPLAIN (and EXPLAIN ANALYZE, which also runs the query) is how you check whether an index is used.

Composite indexes. An index on (country, city) is sorted by country first, then by city within each country. It helps WHERE country = 'DZ' and WHERE country = 'DZ' AND city = 'Oran', but not WHERE city = 'Oran' alone, just as a phone book sorted by last name does not help you find everyone named Karim. This is the leftmost-prefix rule.

Covering indexes. If the index contains every column the query needs, the database can answer from the index alone and skip the table. PostgreSQL calls this an index-only scan, and offers INCLUDE to add extra columns to an index's leaves.

Unique indexes. UNIQUE and PRIMARY KEY constraints are enforced with an index: before inserting, the database checks whether the key already exists.

Trade-offs

Indexes are not free.

  • Slower writes. Every INSERT, DELETE, and every UPDATE that changes an indexed column must update each affected index. A table with ten indexes does a lot of extra work per write.
  • Disk and memory. Indexes take space, and they compete with table data for the cache.
  • Low selectivity. An index on a boolean is_active column where 95% of rows are true rarely helps: reading most of the table through an index is slower than a sequential scan. The query planner knows this and will often ignore such an index.

Common mistakes

  • Wrapping the column in a function. WHERE LOWER(email) = '...' cannot use a plain index on email. Either store normalized values or create an expression index on LOWER(email).
  • Leading wildcards. LIKE '%gmail.com' cannot use a B-tree, because the sorted order is by the first characters. LIKE 'amina%' can, with the right collation or operator class.
  • Type mismatches. Comparing a text column with a number can force a conversion that disables the index.
  • Indexing everything. Add indexes for the queries you actually run, check with EXPLAIN, and remove indexes nobody uses.
  • Forgetting foreign keys. Joins and cascading deletes on a foreign key column usually want an index on that column. PostgreSQL does not create one automatically.

Other kinds of indexes

B-trees are the default, but not the only option. Hash indexes handle equality only. PostgreSQL also offers GIN (for arrays, JSONB and full-text search), GiST (geometric and range data) and BRIN (very large tables whose rows are naturally ordered, like logs by time). Write-heavy engines such as Cassandra and RocksDB use LSM-trees instead, a topic for another article.

In short

  • An index is a sorted copy of some columns with pointers to the rows.
  • A B-tree keeps that sorted data in wide, shallow, balanced pages, so a lookup costs a few page reads even for millions of rows.
  • Sorted, linked leaves make range queries and ORDER BY cheap.
  • Each index speeds up some reads and slows down every write. Index for real queries, and verify with EXPLAIN.

Originally published at abdeldjalilchougui.biz.

Top comments (0)