Database Indexes
An index is an extra data structure that lets a database find rows without reading the whole table, just like the index at the back of a book lets you find a topic without reading every page. Indexes are the single most effective performance tool in a database, and also a common source of slow writes and wasted storage when overused.
Full scan vs index lookup
Without an index, WHERE email = ? must examine every row: O(n). A B-tree index keeps keys sorted in a shallow, wide tree, so a lookup touches only a few pages: O(log n). We can count the work with a sorted list and binary search, which behaves like a B-tree's search:
def full_scan(rows, key):
steps = 0
for row in rows:
steps += 1
if row == key:
break
return steps
def index_lookup(sorted_keys, key):
lo, hi, steps = 0, len(sorted_keys), 0
while lo < hi:
steps += 1
mid = (lo + hi) // 2
if sorted_keys[mid] < key:
lo = mid + 1
else:
hi = mid
return steps
for n in [1_000, 1_000_000, 100_000_000]:
last = n - 1 # worst case for the scan
keys = range(n) # stand-in for the sorted index
scan = full_scan(range(n), last) if n <= 1_000_000 else n # too slow to loop 100M times
print(f"{n:>11,} rows: scan {scan:>11,} rows, index {index_lookup(keys, last):2} comparisons") 1,000 rows: scan 1,000 rows, index 10 comparisons
1,000,000 rows: scan 1,000,000 rows, index 20 comparisons
100,000,000 rows: scan 100,000,000 rows, index 26 comparisons
A real B-tree has hundreds of keys per page, so even a billion rows need only 3 or 4 page reads, and the top levels are almost always cached in memory.
Seeing the planner use an index
Databases show their plan with EXPLAIN. Here SQLite (built into Python) scans the table until we add an index on the filtered column:
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT, country TEXT, created INTEGER)")
db.executemany("INSERT INTO users (email, country, created) VALUES (?, ?, ?)",
[(f"user{i}@example.com", ["DE", "FR", "VN", "US"][i % 4], 20260000 + i % 365)
for i in range(10_000)])
def plan(sql):
return " | ".join(row[3] for row in db.execute("EXPLAIN QUERY PLAN " + sql))
query = "SELECT id, country FROM users WHERE email = 'user42@example.com'"
print("before:", plan(query))
db.execute("CREATE INDEX idx_users_email ON users(email)")
print("after: ", plan(query))
print("result:", db.execute(query).fetchall())before: SCAN users
after: SEARCH users USING INDEX idx_users_email (email=?)
result: [(43, 'VN')]
Composite indexes and the leftmost prefix
An index on (country, created) is sorted by country first, then by date within each country. It helps queries that filter on country, or on country and created, but not on created alone, just as a phone book sorted by last name, then first name can't find everyone called "Anna" quickly.
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT, country TEXT, created INTEGER)")
db.execute("CREATE INDEX idx_country_created ON users(country, created)")
def plan(sql):
return " | ".join(row[3] for row in db.execute("EXPLAIN QUERY PLAN " + sql))
queries = [
"SELECT email FROM users WHERE country = 'VN'",
"SELECT email FROM users WHERE country = 'VN' AND created > 20260100",
"SELECT email FROM users WHERE created > 20260100",
]
for q in queries:
print(q.split("WHERE ")[1])
print(" ->", plan(q))country = 'VN'
-> SEARCH users USING INDEX idx_country_created (country=?)
country = 'VN' AND created > 20260100
-> SEARCH users USING INDEX idx_country_created (country=? AND created>?)
created > 20260100
-> SCAN users
The third query can't use the index's ordering and falls back to a scan. Put the column used for equality first and the range column last.
Covering indexes
If an index contains every column the query needs, the database answers from the index alone and never touches the table rows: a covering index. SQLite's plan says so explicitly:
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE orders (id INTEGER PRIMARY KEY, user_id INTEGER, status TEXT, total INTEGER)")
db.execute("CREATE INDEX idx_user_status ON orders(user_id, status)")
def plan(sql):
return " | ".join(row[3] for row in db.execute("EXPLAIN QUERY PLAN " + sql))
print(plan("SELECT status FROM orders WHERE user_id = 7"))
print(plan("SELECT status, total FROM orders WHERE user_id = 7"))SEARCH orders USING COVERING INDEX idx_user_status (user_id=?)
SEARCH orders USING INDEX idx_user_status (user_id=?)
The cost of indexes
Every index is another sorted structure to update on each INSERT, UPDATE of an indexed column and DELETE. A rough model:
rows_per_s = 5_000
for n_indexes in [0, 2, 5, 10]:
writes = rows_per_s * (1 + n_indexes) # table + each index
print(f"{n_indexes:2} secondary indexes -> {writes:6,} structure updates per second") 0 secondary indexes -> 5,000 structure updates per second
2 secondary indexes -> 15,000 structure updates per second
5 secondary indexes -> 30,000 structure updates per second
10 secondary indexes -> 55,000 structure updates per second
| Index type | Good for | Not for |
|---|---|---|
| B-tree (default) | Equality, ranges, ORDER BY, prefix LIKE 'abc%' |
LIKE '%abc', full-text search |
| Hash | Equality only, very fast | Ranges, sorting |
| LSM-tree (RocksDB, Cassandra) | Very high write rates | Reads may check several levels |
| Inverted index | Full-text search, tags | Ranges on numbers |
| Geospatial (R-tree, geohash) | "Near me" queries | Exact-match lookups |
Tip: Index the columns in your hottest
WHERE,JOINandORDER BYclauses, check the plan withEXPLAIN, and drop indexes no query uses. Low-selectivity columns (a boolean, a status with 3 values) rarely deserve an index on their own.
Test yourself
Roughly how many comparisons does a binary search (or B-tree-like lookup) need in 1,000,000 sorted keys?
- About 20
- About 1,000
- About 500,000
- 1,000,000
An index exists on (country, created). Which query can NOT use it efficiently?
- WHERE country = 'VN'
- WHERE country = 'VN' AND created > 20260100
- WHERE created > 20260100
- WHERE country = 'VN' ORDER BY created
What is a downside of adding many indexes to a table?
- Reads become slower
- Every write must also update each index
- Indexes delete old rows
- Queries return different results