Indexes
Finding rows fast.
Shoply's orders table has ten million rows. Finding one customer's orders means checking every row, unless there's an index. An index is like the index at the back of a book.

- Ten million rows
- Checking every row is slow
- An index, like a book's
Scan vs index
Let's compare. A scan checks every row, one by one. An index is a sorted structure, so we can use binary search to jump straight to the right place. Run it. Finding one order by scanning takes more than six hundred thousand steps. With the index, it takes about twenty.
import bisect
ids = list(range(0, 2_000_000, 2)) # 1 million sorted order ids
target = 1_234_568
steps = 0
for x in ids:
steps += 1
if x == target:
break
print(f"scan: {steps:,} steps")
pos = bisect.bisect_left(ids, target)
print(f"index: about {len(ids).bit_length()} steps, found {ids[pos] == target}")scan: 617,285 steps index: about 20 steps, found True
The cost of indexes
Indexes aren't free. Each one uses extra disk space. And every insert or update must also update every index, so writes get slower. The rule is to index the columns you search and sort by often, like customer ID or email, and not much else.
| key | value |
|---|---|
| Reads | much faster |
| Writes | a bit slower |
| Space | extra storage |
| Rule | index what you search often |
Summary
An index lets a database jump to rows instead of scanning them all. Index columns you search often, but remember each index slows writes. Next, keeping data correct with transactions.
Key takeaways- Scan: every row
- Index: jump straight there
- Costs writes and space