Find the row — why a file scan won't do — point, range and indexed lookups in one file
A SQL engine has to answer point, range, and indexed lookups against ONE file — the only family of structures that can do all three is an ordered tree.
Scene 01
Find the row — why a file scan won't do
- Watch
- Try it
- Predict
- Capture
Three queries fire one after another — point, range, indexed. Watch the cursor walk every row in the file for each one. The counter tells you the cost.
Highlighted lines are the ones running in the diagram right now.
def select_row(file, target_id):# no order to exploit — read the cells in disk orderfor cell in file.cells: # O(N) page readsif cell.rowid == target_id:return cell.row # point hit (still scanned)return None # range / indexed: full file
def insert_row_into_sorted(file, row):# file is kept in PK order on diskpos = bisect_left(file.cells, row.rowid) # O(log N)# make room at pos by sliding the tail one slot rightfor i in range(len(file.cells) - 1, pos - 1, -1):file.cells[i + 1] = file.cells[i] # O(N) writesfile.cells[pos] = rowfile.length += 1
Where this sits in Build a B-tree storage engine (SQLite-style)
Scene 01 of 11, in the The brief act — Why a flat or sorted file isn't enough.. A SQL engine has to answer point, range, and indexed lookups against ONE file — the only family of structures that can do all three is an ordered tree.
Up next. We've decided we need an ordered structure inside the file. But what is the file even, physically? Not bytes addressed individually — the next scene reveals it's a strip of fixed-size pages.
All 11 scenes in Build a B-tree storage engine (SQLite-style) · Every curriculum