AI Hints
Home›System Design Tutorial›Database Families
System Design · Lesson 39 of 120

Indexes

Finding rows fast.

⏱ 2 min read▶ Video at 45:40🎓 Free
Watch this lesson in the System Design courseWatch on YouTube ↗Full System Design course

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.

Indexes
From the video: Indexes
  • 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.

index.pypython
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}")
Output
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.

keyvalue
Readsmuch faster
Writesa bit slower
Spaceextra storage
Ruleindex 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
Next up: Transactions and ACID — all or nothing