avatar
Databases

From Disk Storage to B+ Trees: How Database Indexing Actually Works

Understand database indexes from disk pages to B+ trees, with eight text diagrams, four interactive labs, step-by-step splits, and PostgreSQL EXPLAIN exercises.

Sarvar Musazade25 min read—views

A balanced binary search tree can find a key in O(log n). So why do PostgreSQL and MySQL commonly use B-tree-family indexes? The missing piece is the cost of accessing the next node. Twenty comparisons against values already in memory are inexpensive. Twenty unrelated storage-page requests can be a very different workload.

We will follow one Employee table from persistent storage into memory, build a small index, and turn that index into a balanced multiway tree. Along the way, eight diagrams and four interactive labs let you trace page reads, median promotion, leaf links, and page splits. The goal is to understand why the structure fits the machine, rather than memorize a tree definition.

Reading guide: allow about 18–22 minutes for the article, plus time for the labs. Topics: HDDs, SSDs, RAM, blocks, database pages, indexing, M-way trees, B-trees, and B+ trees. All tiny byte sizes and page layouts below are teaching models unless explicitly identified as real engine behavior.

1. RAM and persistent storage reward different designs

RAM is the working space for programs and cached database pages. It supports fast random access through the CPU cache and memory hierarchy. Ordinary RAM is volatile: its contents disappear when power is lost. A database buffer pool, also called a buffer cache in some systems, uses RAM to keep frequently accessed pages available.

HDDs and SSDs preserve database files across restarts. An HDD must position a moving head and wait for the relevant region of a rotating platter. An SSD removes those mechanical delays, but accessing storage still involves more machinery than reading a value already present in memory. We do not need one universal latency ratio to see why fewer storage requests can help.

A tree designed around one key per separately accessed page would use the page poorly. A database-oriented tree packs many keys into each page, narrowing the search substantially before requesting the next page. Caching matters too: a search may visit three index pages while reading only one of them from storage, because the other two are already cached.

Diagram 1 · RAM holds cached working pages; persistent HDD or SSD storage supplies pages missing from memory

RAM / BUFFER POOL                    PERSISTENT STORAGE+----------------------------+       +----------------------------+| Cached table and index     |       | HDD: platters + moving head|| pages; fast working memory |       | SSD: flash; no moving head || Volatile across power loss|       | Retains files across restart|+----------------------------+       +----------------------------+       ^                                         |       +--- Load a missing page into RAM --------+       |       +-- CPU compares keys in the cached pageLogical page visit = algorithm needs a page.Storage request    = page is missing from the DBMS buffer pool.An OS cache may still satisfy that request without device I/O.

Storage reads and logical page visits are different measurements. A cached page needs no new storage read.

2. Tracks, sectors, blocks, and offsets

A traditional HDD has magnetic platter surfaces. A track is a circular path on a surface; a sector is a subdivision of a track. Modern operating systems normally address storage through logical block addresses, rather than asking the drive for a particular track and angle. The drive maps those addresses to its own physical organization.

The word block belongs to several layers. A device exposes logical blocks; a file system allocates and manages file data; a DBMS defines pages inside its files. Those units can differ in size. A logical sector size such as 512 or 4,096 bytes does not mean every database page has that same size.

An offset is a position relative to a starting point. In a hypothetical 512-byte block holding four fixed 128-byte records, their starting offsets are 0, 128, 256, and 384. A row locator can combine a page identifier with a slot number. The slot directory then identifies the row inside the page; the locator need not be a raw machine-memory address.

SSDs have no tracks, platters, or moving heads. Their flash programming and erasure rules also differ from the logical block interface presented to software. The lesson that survives both devices is to organize useful work around pages and locality, while letting the storage stack manage the physical details.

Diagram 2 · A schematic HDD platter with tracks and sector boundaries beside a logical 512-byte block with four 128-byte records at offsets 0, 128, 256 and 384

HDD SURFACE                         LOGICAL 512-BYTE BLOCK  Concentric paths = tracks         +----------------------------+  Track subdivisions = sectors      | Employee 1: 128 B | off   0 |                                    | Employee 2: 128 B | off 128 |  The drive maps logical            | Employee 3: 128 B | off 256 |  addresses to its physical         | Employee 4: 128 B | off 384 |  storage organization.             +----------------------------+Offset = byte position relative to the start of the block.Row locator can identify a page plus a slot within that page.Device sector / logical block / DBMS page are separate layers.A DBMS page need not equal one physical sector.SSDs have no platter tracks or moving read/write heads.

Physical device addressing and DBMS page layouts are separate layers; the arrow is conceptual.

3. A database page is a container for useful work

A table page can contain a header, row-location slots, actual rows, and unused space. An index page holds an index-specific layout, such as separator keys and child pointers or leaf entries. When a needed page is missing from the DBMS cache, the storage stack supplies it to memory. Read-ahead and operating-system caching can make the physical I/O larger or cheaper than this simplified description suggests.

PostgreSQL usually uses 8 KiB pages. Its page format includes a header, item identifiers, free space, items, and, for some page types, special space. A slot-based layout allows row locations to be managed within a page. PostgreSQL: database page layout

For the next calculations, a page is exactly 512 bytes and has no overhead. We also assume that rows have fixed sizes and never span pages. These choices make the arithmetic visible; they are not claims about a PostgreSQL or InnoDB file. Whenever division produces a fractional number of pages, round up.

4. Pack the Employee table into pages

sql
CREATE TABLE Employee (    eid INT PRIMARY KEY,    name VARCHAR(50),    dept VARCHAR(10),    section VARCHAR(8),    address VARCHAR(50));

Imagine 100 employees with IDs 1 through 100. For example, employee 1 is John in IT, employee 2 is Tom in HR, and employee 3 is Anil in IT. Our invented storage widths are eid = 10 bytes, name = 50, dept = 10, section = 8, and address = 50. That totals 128 bytes. The 10-byte ID is a toy choice: SQL INT is not being assigned its actual representation here, and VARCHAR declarations are not fixed-width byte allocations.

Toy record: 10 + 50 + 10 + 8 + 50 = 128 bytesRows per page = floor(512 / 128) = 4Table pages = ceil(100 / 4) = 25P1:   employees  1–4P2:   employees  5–8...P25:  employees 97–100

The page labels assume ascending ID order for this example only. A heap table does not promise physical ordering by primary key. Inserting, updating, and deleting rows can change which pages contain them. An index supplies the current locator instead of relying on the arithmetic relationship between an ID and its page.

Diagram 3 · A proportionally divided 128-byte employee record and 25 pages, each holding four employees; page 25 contains IDs 97 through 100

ONE TOY RECORD+--------+--------+--------+---------+---------+| eid    | name   | dept   | section | address || 10 B   | 50 B   | 10 B   |  8 B    | 50 B    |+--------+--------+--------+---------+---------+Total = 128 bytes (illustrative widths, not real SQL type sizes)512 / 128 = 4 rows per pageceil(100 / 4) = 25 table pagesP1:   1-4      P6:  21-24    P11: 41-44    P16: 61-64    P21: 81-84P2:   5-8      P7:  25-28    P12: 45-48    P17: 65-68    P22: 85-88P3:   9-12     P8:  29-32    P13: 49-52    P18: 69-72    P23: 89-92P4:  13-16     P9:  33-36    P14: 53-56    P19: 73-76    P24: 93-96P5:  17-20     P10: 37-40    P15: 57-60    P20: 77-80    P25: 97-100Toy assumptions: fixed rows, no page headers or unused space.Ascending physical ID order is an example, not a heap-table guarantee.

The SQL INT type is not 10 bytes. These byte widths are deliberately invented for arithmetic; real rows include overhead.

5. Why scanning can be expensive

sql
SELECT * FROM Employee WHERE eid = 97;

If we deliberately ignore indexes, a scan may examine all 25 pages to locate employee 97. That is a small workload, but the same idea becomes costly across millions of rows. A missing key can also require examining the entire table. SQL does not promise that a scan will stop after reading one particular physical page.

There is an important detail in the CREATE TABLE above: PostgreSQL and InnoDB normally create an index for a primary key. Therefore, the no-index story is a hypothetical baseline, not the expected execution plan for that exact schema. Later, the runnable PostgreSQL exercise uses a separate table without a primary key to make the before-and-after comparison real.

A scan is not inherently a mistake. Reading a large fraction of a table in page order can cost less than following an index to many scattered rows. The first question is whether an index can identify a small useful subset of the data; the second is whether that access path is cheaper for the actual query.

6. A flat index: smaller entries, fewer pages

A textbook index lets us look up a subject and jump to the relevant page. A database index plays a similar role: it stores search keys plus enough information to locate associated rows. In our first design, each employee contributes one entry containing a 10-byte key and a 6-byte row locator. Real engines use their own formats, and duplicate keys can change how entries are represented.

Index entry = 10-byte key + 6-byte locator = 16 bytesEntries per page = floor(512 / 16) = 32Index pages = ceil(100 / 32) = 4I1:  1–32     I2: 33–64I3: 65–96     I4: 97–100Sequential flat-index lookup of 97:I1 → I2 → I3 → I4 → table page P254 index-page reads + 1 table-page read = 5 cold page reads

The index reduces the amount of information we inspect because it excludes most row fields. But it still needs its own search strategy. Our five-read example intentionally scans index pages in order. A sorted array of entries could use binary search; the reason to move toward a tree is also to handle growth, insertion, deletion, and ordered traversal efficiently.

Diagram 4 · Four flat-index pages cover IDs 1–32, 33–64, 65–96 and 97–100

FLAT INDEX                              TABLEI1: [keys  1-32]                         P1:  [employees 1-4]       |                                P2:  [employees 5-8]I2: [keys 33-64]                         ...       |I3: [keys 65-96]       |I4: [keys 97-100] -- locator for 97 --> P25: [employees 97-100]Entry = 10-byte key + 6-byte locator = 16 bytes512 / 16 = 32 entries per pageceil(100 / 32) = 4 index pagesSequential cold lookup of 97:I1 -> I2 -> I3 -> I4 -> P25 = 5 page readsA sorted flat index could instead use binary search.

This is a deliberately sequential flat-index search. A sorted index could also use binary search.

7. Multilevel indexing: put an index above the index

Add a small directory containing the starting key and page pointer for each lower-level index page. The complete directory for our 100 employees has four entries: 1 → I1, 33 → I2, 65 → I3, and 97 → I4. To find 70, choose the greatest starting key no larger than 70: that is 65. Read I3, find its row locator, then read the table page.

Directory: [1 → I1 | 33 → I2 | 65 → I3 | 97 → I4]                               │                               ▼                         I3: keys 65–96                               │                               ▼                         Employee 70Cold lookup: directory + one index leaf + one table page = 3 reads

If the directory becomes too large, add another directory above it. This is the central idea of multilevel indexing. The hard part is maintenance: a full lower page might split, creating a new pointer in its parent; that parent might also become full. A balanced tree supplies rules for keeping these levels shallow and consistent as the table changes.

Interactive lab

Lab 1 · Count page accesses, then warm the cache

Compare four access paths for employee 97. Toy layout: 25 table pages, four flat-index pages, and an optional one-page directory. Each scenario starts independently. Counts exclude metadata, visibility work, and read-ahead.

Try this: Predict the number of logical page visits and buffer-miss loads for each path. Why can a warm three-page lookup need zero loads?

Show hint

A logical visit means the algorithm needs a page. A buffer-miss load means that page is missing from DBMS RAM; the operating system may still cache it.

Search algorithm
Find eid = 97
Buffer pool
Empty
Persistent pages
0 buffer-miss loads
Logical page visits
0
Search algorithmBuffer poolPersistent pagesLogical page visits

Ready

Make a prediction, then start the experiment.

A step-by-step model. Switch experiments to compare outcomes.

8. From binary search trees to M-way search trees

A binary search tree node uses one key to divide values into two child ranges. An M-way search tree permits up to M children and M − 1 sorted keys. Three keys, such as [20 | 40 | 60], divide the remaining values into four ranges. For distinct keys, values below 20 go left, values between 20 and 40 enter the second child, values between 40 and 60 enter the third, and values above 60 go right.

To search for 75 in the diagram, compare it with the root separators and enter [70 | 80 | 90]. At that leaf, 75 falls between existing keys and is absent. Only two nodes were visited. Searching within a large node can itself use binary search or another engine-specific strategy; the practical benefit comes from making many routing decisions with one loaded page.

Diagram 5 · A 4-way search tree with root keys 20, 40, 60 and four correctly ordered leaf children

                       [20 | 40 | 60]                      /      |      |       \                     /       |      |        \                 [5 | 10] [25 | 30] [45 | 50] [70 | 80 | 90]Child ranges, left to right (distinct keys):  key < 20  20 < key < 40  40 < key < 60  key > 60Search 75: root -> rightmost child, because 75 > 60.At the leaf, 70 < 75 < 80: no matching entry.Only two nodes were visited.

For distinct keys, a classic M-way search can also finish at a key in the internal node.

9. Multiple children do not guarantee balance

Suppose an ordinary 4-way tree uses a simple insertion policy: fill the current node up to three keys, then descend to or create the appropriate child. Inserting ascending values can produce a rightward chain. The structure obeys the search-order rule, but it has no rule keeping all root-to-leaf paths equally short.

[10 | 20 | 30]              \               [40 | 50 | 60]                             \                              [70 | 80 | 90]

For a fixed maximum node capacity, continued insertion can make height grow proportionally to the number of keys. The problem is not the use of multiple keys; it is the missing balance guarantee. Also notice that our nine-key chain has only three nodes: a tiny example need not make the B-tree visibly shorter. Balance gives a bound as the input grows, rather than a promise to win every small comparison.

10. B-tree rules keep paths short

A B-tree is a balanced multiway search tree. Keys stay sorted inside each node; child subtrees obey the key ranges; all leaves have the same depth; and non-root nodes obey minimum occupancy rules. The root is special because a newly created tree must be allowed to begin small. Splitting, redistribution, and merging preserve these invariants as keys change.

Definitions of order differ between textbooks, so we will specify minimum degree t = 2. Every node has at most 2t − 1 = 3 keys. A non-root node has at least t − 1 = 1 key. An internal node with k keys has k + 1 children, so non-root internal nodes have between two and four children. A nonempty root has at least one key; an internal root has at least two children.

In the classic B-tree model, a key may carry its associated record or row locator even in an internal node. A search can finish there. We will show keys alone in the insertion drawings so that the mechanics remain readable. This is a teaching B-tree algorithm, not a claim that a particular database uses exactly these split timings or occupancy thresholds.

11. Insert 10 through 90: split before descending

We use top-down insertion. Before descending into a full child, split it and move its median into the parent. If the root is full at the start of an insertion, create a new root and split the old one. This guarantees that the destination leaf has room. The example inserts 10, 20, 30, 40, 50, 60, 70, 80, and 90.

Build the first root, then insert 40

The first three insertions produce [10 | 20 | 30]. To insert 40, split that full root: promote 20, leave [10] on the left, and create [30] on the right. Now insert 40 into the right leaf, giving root [20] with leaves [10] and [30 | 40]. All leaves moved to the same new depth together.

Insert 50 and 60

Inserting 50 produces [30 | 40 | 50] in the right leaf. Before inserting 60 there, promote its median 40. The root becomes [20 | 40], with children [10], [30], and [50]. Insert 60 into the final child to get [50 | 60]. No leaf became deeper than its siblings.

Insert 70 and 80

Insert 70 into [50 | 60], giving [50 | 60 | 70]. Before descending for 80, split that leaf and promote 60. The root becomes [20 | 40 | 60], with children [10], [30], [50], and [70]. Then insert 80 into [70], giving [70 | 80].

Insert 90 and grow the root

The root is now full. Our top-down algorithm splits it before descent even though the eventual leaf still has room. Promote 40 to a new root; [20] and [60] become internal children. Their leaves remain in order. Finally insert 90 into [70 | 80], giving [70 | 80 | 90]. Other correct insertion policies can produce different valid shapes.

Diagram 6 · Six panels show B-tree insertion of 10 through 90, ending with root 40, internal nodes 20 and 60, and leaves 10, 30, 50, and 70 80 90

1. Insert 10, 20, 30        2. Insert 40: promote 20   [10 | 20 | 30]                     [20]                                     /    \                                   [10] [30 | 40]3. Insert 50               4. Insert 60: promote 40          [20]                      [20 | 40]         /    \                    /    |     \       [10] [30 | 40 | 50]       [10]  [30]  [50 | 60]5. After inserting 70 and 80: promote 60                    [20 | 40 | 60]                   /     |     |      \                 [10]  [30]  [50]  [70 | 80]6. Insert 90: split full root first, promoting 40                         [40]                        /    \                     [20]    [60]                    /   \    /    \                  [10] [30] [50] [70 | 80 | 90]Minimum degree t = 2; at most three keys per node.Classic B-tree: promoted median moves out of the child.All final leaves are at the same depth.

The promoted median leaves its old node in this classic B-tree. All final leaves remain at the same depth.

Interactive lab

Lab 2 · Predict the promoted median

Classic B-tree, minimum degree t = 2, with at most three keys per node. State cards show multi-key nodes; the existing binary-tree player is intentionally not used for this multiway structure. Each scenario starts independently.

Try this: Before each split, predict the median and whether the tree gains a level. Compare an ordinary leaf split with a root split.

Show hint

A three-key node [a | b | c] splits into [a] and [c]; b moves into the parent. Only splitting the root creates a new level.

Root
Not initialized
Internal level
None
Leaves, left to right
Not initialized
Promoted key
None
Levels
Not initialized

Ready

Make a prediction, then start the experiment.

A step-by-step model. Switch experiments to compare outcomes.

12. Search cost: height matters more than a slogan

                 [40]                /    \             [20]    [60]            /   \    /   \          [10] [30] [50] [70 | 80 | 90]Search 70: [40] → [60] → [70 | 80 | 90]

Searching for 70 visits three nodes: compare against 40, follow the right child; compare against 60, follow the right child; find 70 in the leaf. If each node is one page and all are missing from memory, that is three tree-page loads. Fetching the full employee can require a separate table page. Finding an internal key in a classic B-tree may stop earlier.

For fixed node capacity, balanced B-tree search remains O(log n) in the usual comparison model. In a page-I/O model, high fanout makes the base of the logarithm matter. With fanout near 100, level widths can grow as 1, 100, 10,000, and 1,000,000 nodes. These are node counts at successive levels, not the number of records the entire tree holds.

Real fanout comes from the page budget. In a simplified internal page with P bytes, H header bytes, K-byte separator keys, and C-byte child pointers, m children need H + (m − 1)K + mC bytes. With P = 8,192, H = 128, K = 16, and C = 8, the inequality allows m ≤ 336. That is an upper bound for this model; actual entry formats, variable keys, and occupancy reduce effective fanout.

13. Why an AVL or red-black tree is a different tradeoff

A balanced binary search tree containing one million keys has roughly 20 levels. A disk-oriented tree with hundreds of child pointers per internal page can be far shallower. If each node visit required a different page, this would be a large difference in storage work even though both structures have logarithmic search complexity.

This comparison is illustrative. A system can pack multiple binary-tree nodes into a page, and an in-memory application may prefer a binary tree for other reasons. CPU caches, pointer overhead, update patterns, and implementation complexity all matter. B-tree-family indexes fit page-based storage because many useful keys travel together and a small number of page visits narrows the search.

14. B+ trees move all data entries to the leaves

In the classic B-tree model, internal keys can carry records or record locators. In a B+ tree, internal nodes carry separator keys and child pointers for navigation, while searchable data entries live at the leaf level. A separator may repeat a key that also appears in a leaf. Finding an equal separator therefore does not finish the row lookup: navigation continues downward.

Our B+ tree uses root [30 | 60] and leaves [10 | 20], [30 | 40 | 50], and [60 | 70 | 80]. We adopt a precise routing convention: the first child contains keys less than 30; the middle contains 30 ≤ key < 60; the right contains keys at least 60. Equality follows the right side of the matching separator. This is a distinct teaching tree, separate from the B-tree built by insertion above.

Search for 70: visit the root, choose the rightmost child, and find the entry in [60 | 70 | 80]. Search for 60: follow that same child even though 60 appears in the root. Search for 75: reach the leaf, check between 70 and 80, and report no matching entry. Production engines also handle duplicate keys, concurrency, and row visibility; we omit those mechanics from the drawing.

Diagram 7 · A classic B-tree keeps a row locator alongside internal key 30

CLASSIC B-TREE             [30 + row locator]                /           \           [10 | 20]    [40 | 50 | 60]Search for 30 can finish at the root.B+ TREE                        [30 | 60]                       /    |     \                      /     |      \                [10 | 20] [30 | 40 | 50] [60 | 70 | 80]                    |           |              |                    +---------->+------------->+--> endInternal separators guide navigation; data entries live in leaves.Equality follows the right side of a separator in this example.Range 30-70:  root -> middle leaf: return 30, 40, 50       -> next leaf:   return 60, 70; stop before 80Separator 30 remains a searchable entry in the middle leaf.

For this B+ tree, equality follows the right side of a separator. Range 30–70 returns 30, 40, 50, 60, 70.

15. Linked leaves turn a search into a range scan

sql
SELECT *FROM EmployeeWHERE eid BETWEEN 30 AND 70ORDER BY eid;

First descend to the leaf that could contain 30. Return 30, 40, and 50 from the middle leaf. Then follow its next-leaf link and return 60 and 70. Stop when the next entry is 80, because it exceeds the inclusive upper bound. The leaf links avoid restarting at the root for every result. Their ordering is logical; neighboring leaves do not have to occupy adjacent disk blocks.

For this tree, the range operation visits one root and two leaves: three index pages. This does not include any table pages needed for SELECT *. Five matching entries might point into one cached table page or several scattered pages. A narrow index range is useful, but the full query cost still depends on row retrieval.

B+ trees support equality, ordered traversal, and inequalities over sortable keys. Prefix predicates need suitable indexing rules: a compatible index may help a search such as LIKE 'Ali%', while a leading wildcard such as LIKE '%Ali' generally cannot supply the same starting point. Composite indexes introduce another ordering question because their key order follows the indexed column sequence.

In PostgreSQL, B-tree is the default CREATE INDEX method and supports equality and range predicates. Prefix pattern matching also depends on collation and operator-class details. PostgreSQL: index types

Interactive lab

Lab 3 · Search once, then follow the leaves

Distinct-key B+ tree with root [30 | 60]. L1=[10 | 20], L2=[30 | 40 | 50], L3=[60 | 70 | 80]. Equality follows the right side of a separator. Counts cover index pages only.

Try this: Compare equality, a missing key, and range 30–70. Does finding separator 60 at the root let you return an employee?

Show hint

Internal separators route searches. Only leaves carry data entries. BETWEEN includes both endpoints.

Root separators
[30 | 60]
Leaf L1
[10 | 20] → L2
Leaf L2
[30 | 40 | 50] → L3
Leaf L3
[60 | 70 | 80] → end
Matching keys
None
Index pages visited
0
Root separatorsLeaf L1Leaf L2Leaf L3Matching keysIndex pages visited

Ready

Make a prediction, then start the experiment.

A step-by-step model. Switch experiments to compare outcomes.

16. A B+ leaf split copies a separator upward

A B+ leaf split has a useful distinction from the classic B-tree split above. Suppose leaves hold at most three entries and we insert 65 into [60 | 70 | 80]. In a simple bottom-up model, an overflowing temporary leaf contains [60 | 65 | 70 | 80]. Split it into [60 | 65] and [70 | 80], repair the neighboring leaf links, and copy 70 into the parent as the separator for the new right leaf. The data entry for 70 remains in its leaf.

With parent [30 | 60], this produces [30 | 60 | 70]. If the parent is also full, a split can propagate upward; splitting the root creates a new root. Internal-node splits move separators according to different rules from leaf splits. Deletion can require occupancy repair in textbook trees, although production engines use their own page-reclamation and maintenance policies.

Interactive lab

Lab 4 · Copy the separator, keep the leaf entry

Teaching B+ tree: leaves allow three entries; internal nodes allow three separators. Bottom-up insertion is used here, separately from the top-down classic B-tree lab. Each scenario resets to its own initial tree.

Try this: Predict the new separator when 65 enters a full leaf. Why must key 70 remain in the leaf after it appears in the parent?

Show hint

All B+ data entries belong to leaves. Copy the minimum key of the new right leaf into this parent; do not remove its data entry.

Parent separators
Not initialized
Target leaf
Not initialized
New right leaf
None
Leaf links
Not initialized
Action
Awaiting insertion

Ready

Make a prediction, then start the experiment.

A step-by-step model. Switch experiments to compare outcomes.

17. What PostgreSQL and InnoDB actually mean by an index

Database product terminology does not always follow the textbook distinction literally. A product may call its implementation B-tree while using leaf data entries and sibling links associated with the B+ model. Use B-tree family when discussing the broader design, and check the engine documentation before assuming an exact page format or insertion algorithm.

PostgreSQL describes its B-tree indexes as a multilevel structure. Internal pages direct searches to children, leaf pages hold tuples pointing to table rows, and pages at each level have sibling links. Its production implementation also includes maintenance and concurrency details beyond our toy trees. PostgreSQL: B-tree implementation

In InnoDB, the clustered index stores the row data at its leaves, normally organized by the primary key. Secondary index entries include the primary-key columns, which identify rows in that clustered index. A secondary lookup may therefore lead to a second tree search rather than directly to one physical row address. MySQL: clustered and secondary indexes

PostgreSQL stores its indexes separately from the table heap. A covering index can supply all requested columns, but an index-only scan still has visibility requirements. The visibility map can allow heap visits to be skipped for all-visible pages; otherwise the executor must check the heap. PostgreSQL: index-only scans

These differences explain why “find the leaf, then read one row page” is a helpful starting picture but not a universal execution trace. Index entries may cover the query, hold the complete clustered row, or supply another lookup key. Snapshot visibility, duplicate entries, and cached pages also affect the work.

18. Try it in PostgreSQL: observe the plan before and after

The four embedded labs are deterministic teaching simulations. This optional SQL exercise lets the real optimizer choose a plan. Run it in a PostgreSQL session; the temporary table disappears when that session ends. We use 200,000 rows because a 100-row table is often small enough that a sequential scan is reasonable even with an index.

sql
-- Separate table: deliberately no PRIMARY KEY and no initial indexes.CREATE TEMP TABLE employee_index_lab (    eid INT,    name VARCHAR(50),    dept VARCHAR(10),    section VARCHAR(8),    address VARCHAR(50));INSERT INTO employee_index_labSELECT g, 'Employee ' || g,       CASE WHEN g % 100 = 0 THEN 'IT' ELSE 'Sales' END,       'A', 'Street ' || gFROM generate_series(1, 200000) AS g;ANALYZE employee_index_lab;-- Baseline: there is no index on eid.EXPLAIN (ANALYZE, BUFFERS)SELECT * FROM employee_index_lab WHERE eid = 199997;CREATE INDEX employee_index_lab_eid_idxON employee_index_lab(eid);ANALYZE employee_index_lab;-- Same query, now with an index available.EXPLAIN (ANALYZE, BUFFERS)SELECT * FROM employee_index_lab WHERE eid = 199997;

Before indexing, expect a sequential scan with many rows removed by the filter. Afterward, an index scan is a likely choice for the one-row predicate, though exact plans and costs depend on the server. Compare the scan type, Index Cond versus Filter, rows examined, and buffer counters. Do not copy an execution time from someone else as a promised result for your machine.

sql
CREATE INDEX employee_index_lab_dept_idxON employee_index_lab(dept);ANALYZE employee_index_lab;-- IT matches 2,000 rows: 1% of the table.EXPLAIN (ANALYZE, BUFFERS)SELECT * FROM employee_index_lab WHERE dept = 'IT';-- Sales matches 198,000 rows: 99% of the table.EXPLAIN (ANALYZE, BUFFERS)SELECT * FROM employee_index_lab WHERE dept = 'Sales';-- A narrow ordered range can use the eid index.EXPLAIN (ANALYZE, BUFFERS)SELECT eid FROM employee_index_labWHERE eid BETWEEN 70000 AND 70010ORDER BY eid;

Predict the contrast before executing: the selective IT query may use an index or bitmap strategy, while Sales may favor a sequential scan. Both use the same indexed column. This illustrates that the existence of an index does not force its use. The range query demonstrates ordered access, but PostgreSQL may still fetch heap tuples to check visibility, even though only eid is selected.

EXPLAIN shows the chosen plan; EXPLAIN ANALYZE executes it and reports observed behavior. BUFFERS helps inspect buffer activity. For this temporary table, look for local-buffer counters rather than assuming shared-buffer counters. A PostgreSQL buffer read can still be served by the operating-system cache, so it is not proof of a physical device access. PostgreSQL: using EXPLAIN

Rerun the indexed query and observe caching, but do not call the first run a guaranteed cold-disk test: inserting the data and building the index already touched those pages. The exercise is useful for comparing access paths and understanding counters. It is not a controlled storage benchmark. The exact toy counts from Lab 1 are not expected PostgreSQL plan output.

19. Index maintenance is part of every write

An index takes storage and cached memory, and writes must keep it consistent with the table. Inserting an employee may add entries to several indexes. Updating an indexed department value can require replacing the old index entry, while deletions need engine-specific cleanup. A page with insufficient room may split and require a new separator in its parent; that work can propagate upward.

Wider index keys generally leave room for fewer entries on each page. Covering indexes can reduce row fetches, but extra included columns also enlarge the leaves. Adding every possible index can therefore increase write work and memory pressure. Choose indexes around actual predicates, join conditions, ordering, and measured plans rather than assuming that more is always better.

For the end-to-end lookup below, assume an unclustered index and a row that must be fetched from the table. The application submits SQL; the planner selects the access path; the executor visits cached or newly loaded index pages; the leaf provides a locator; and the DBMS retrieves and checks the row before returning it. No arrow in the diagram promises a new device read.

Diagram 8 · An application submits eid equals 70

1. APPLICATION   SELECT * FROM Employee WHERE eid = 70                  |                  v2. DBMS QUERY PLANNER   Choose an index access path                  |                  v3. BUFFER POOL / RAM   Root [30 | 60] -> right leaf [60 | 70 | 80]                  |                         ^                  |                         |                  |        PERSISTENT STORAGE                  |        Load pages missing from RAM                  v4. ROW LOOKUP   Leaf entry 70 -> locator -> table page containing Employee 70                  |                  v5. RESULT   Check row visibility; return the employee through the DBMSCached pages do not require new storage reads.Conceptual unclustered index: a clustered leaf can hold the row itself.

Conceptual unclustered lookup. In a clustered index, the leaf may contain the row itself.

20. Compare the structures and keep the right cost model

Property                 M-way tree       Classic B-tree    B+ treeMultiple keys per node   Yes              Yes               YesBalance guaranteed       No               Yes               YesAll leaves same depth    Not required     Yes               YesMinimum occupancy        Not inherent     Defined           DefinedData in internal nodes   Possible         Possible          No data entriesAll data entries at leaf Not required     Not required      YesLinked leaf scans        Not required     Not required      CommonRange queries            Shape-dependent  Efficient         Especially suited

The path from storage to B+ trees is now continuous. Persistent data is managed in pages. An index packs search keys more densely than full rows. A directory above those pages reduces the search. Multiway branching makes each visited page useful, balance bounds the number of levels, and leaf links allow a search to continue through an ordered range.

The central insight is about page work: B-tree-family structures organize searching and updates around a small number of useful page visits. Comparisons still matter, but O(log n) alone does not describe the cost of fetching scattered data. When reading a query plan, separate index navigation, table access, cache hits, buffer reads, and the number of rows returned.

Check your understanding: Why is a 512-byte page not necessarily a physical sector? Why is our SQL primary-key example already indexed? Why does finding separator 60 not finish a B+ lookup? Why can a range scan visit only three index pages yet need several table pages? Why can Sales use a sequential scan while IT uses the same available index? Revisit the matching lab or SQL example until you can explain each answer.

Comments (0)

0/1000

Loading comments...