Database indexes
The conceptWhy a database finds one customer among millions in milliseconds
A database index is a separate, sorted copy of one or more columns, where each entry points to the row it came from. Without one, the query WHERE email = 'ana@x.com' has to do a full table scan: read every row and check it.
With an index on email, the emails sit sorted in a B-tree, each paired with a row ID, the row's address in the table. The database walks the tree to 'ana@x.com', reads its row ID and fetches just that row.
Like the index at the back of a book, it gives you a page number instead of making you read every page. The price is extra disk space, and every write has to update the index too.
What it’s forEstimates how many disk pages a lookup reads with a B-tree index, compared with scanning the whole table.
index lookup ≈ log_b(N) page reads, full scan ≈ all N rows
- N
- number of rows in the table, e.g. 1,000,000
- b
- fan-out: how many keys fit on one index page, often 100s
- log_b(N)
- the height of the tree: how many levels you walk from root to leaf
What it givesA handful of page reads per lookup, even for huge tables, instead of reading every row.
- N = 1,000,000 rows, b = 100 keys per page
- 100 × 100 × 100 = 1,000,000, so log₁₀₀(N) = 3 levels
- About 3 index pages + 1 table page, versus checking a million rows