Searching — a cursor descends the tree — one page I/O per tree level
A point query reads exactly ONE page per tree level — three I/Os to find one row in a tree of millions, even on a miss.
Scene 3 left you with a static tree — labeled, sized, but never used. Now we run our first SELECT through it and count pages read.
Scene 04
Searching — a cursor descends the tree
- Watch
- Try it
- Predict
- Capture
SELECT WHERE id=42. The cursor lands on the root, binary-searches its separator keys, picks one child, and drops down. Each visited page is one disk I/O. Watch the counter.
Highlighted lines are the ones running in the diagram right now.
def search(root_page, target):cursor = read_page(root_page) # +1 I/O at rootio_count = 1while cursor.is_interior:child_idx = binary_search(cursor.keys, target)cursor = read_page(cursor.children[child_idx])io_count += 1 # +1 I/O per levelreturn scan_leaf(cursor, target) # local scan, no I/O
def binary_search(keys, target):lo, hi = 0, len(keys)while lo < hi:mid = (lo + hi) // 2if target < keys[mid]:hi = mid # target lives in left halfelse:lo = mid + 1 # target lives in right half# missing keys land past every separator → rightmost childreturn lo # index of the chosen child
Where this sits in Build a B-tree storage engine (SQLite-style)
Scene 04 of 11, in the Anatomy act — Pages, the tree of pages, and how a search descends.. A point query reads exactly ONE page per tree level — three I/Os to find one row in a tree of millions, even on a miss.
Up next. Lookups are cheap: 3 page reads in a tree of millions. But every INSERT must also descend to its home leaf — and what happens when that leaf is FULL? The next scene splits a leaf for the first time.
All 11 scenes in Build a B-tree storage engine (SQLite-style) · Every curriculum