How Database Indexes Work
Why one line of SQL can turn a 3-second query into 3 milliseconds.
Without an index, finding a row means scanning every row. An index is a sorted, tree-shaped copy of a column that lets the database jump to matches in logarithmic time.
Legend — how to read this diagram
The B-tree behind most indexes
- Sorted structure. Keys are kept in order across a balanced tree of pages.
- Log-time search. Each step halves the search space, so millions of rows take only a handful of hops.
- Range-friendly. Because keys are sorted,
BETWEENandORDER BYcome nearly free. - Points to rows. Leaves hold pointers (or the row itself) so the engine fetches only what matches.
The cost of indexes
Writes get slower. Every insert/update must also update each index.
They use space. An index is a second copy of the indexed columns.
Order matters. A composite index on (a, b) helps queries on a, or a+b — but not b alone.
An index trades some write speed and disk for enormous read speed — a pre-sorted map to your data.
No comments:
Post a Comment