Database Index Basics
What you will learn
- What a full table scan is and why it gets slow
- What an index is, using the book analogy
- How to see whether a query uses an index
- Why an index makes a search much faster
1. The slow way: look at every row
Suppose a shop has 100,000 orders and you ask: "show every order from customer 1234". If the database has nothing to help it, it must open every row and check the customer_id. This is called a full table scan. It works, but the work grows with the table: ten times more rows means about ten times more checking.
2. The idea of an index
At the back of a book there is an index: an alphabetical list of words, each with page numbers. To find "tax" you do not read the whole book; you look in the index and jump to the pages.
A database index is the same idea. It is a separate, sorted structure that lists the values of one or more columns and where the matching rows are. When a query asks for customer_id = 1234, the database looks in the index and jumps straight to those rows.
| Book | Database |
|---|---|
| the pages | the rows of the table |
| the index at the back | an index on a column |
| find the word in the index, then turn to the page | find the value in the index, then fetch the row |
| reading the whole book | a full table scan |
3. See it happen
All the examples in this chapter use one table of made-up orders. Here is the code that builds it, plus two small helpers (the same code is used in every lesson of the chapter, so we will not repeat it each time):
import sqlite3, time
CITIES = ["Dhaka", "Khulna", "Sylhet", "Rajshahi", "Barishal", "Chattogram", "Rangpur", "Mymensingh"]
def build(n=100000):
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER, city TEXT, status TEXT, amount INTEGER, placed TEXT)")
rows = []
for i in range(1, n + 1):
cust = (i * 7919) % 5000 + 1
rows.append((i, cust, CITIES[cust % 8], "shipped" if i % 10 else "pending", (i * 37) % 1000,
"2026-%02d-%02d" % (i % 12 + 1, i % 28 + 1)))
con.executemany("INSERT INTO orders VALUES (?,?,?,?,?,?)", rows)
con.commit()
return con
def plan(con, sql, args=()):
for r in con.execute("EXPLAIN QUERY PLAN " + sql, args):
print(r[3])
def timeit(con, sql, args=(), reps=20):
t = time.perf_counter()
for _ in range(reps):
con.execute(sql, args).fetchall()
return (time.perf_counter() - t) / reps * 1000
Now ask for one customer's orders, and look at the query plan, the database's description of how it will answer. EXPLAIN QUERY PLAN is SQLite's way to show it (lesson 7.6 explains it in detail):
con = build()
print(con.execute("SELECT COUNT(*) FROM orders").fetchone())
q = "SELECT * FROM orders WHERE customer_id = 1234"
print(len(con.execute(q).fetchall()))
plan(con, q)
print("before: %.3f ms" % timeit(con, q))
(100000,)
20
SCAN orders
before: 4.391 ms
SCAN orders means a full table scan: all 100,000 rows were looked at to find 20. Now create an index on customer_id and ask again:
con.execute("CREATE INDEX idx_orders_customer ON orders (customer_id)")
plan(con, q)
print("after: %.3f ms" % timeit(con, q))
SEARCH orders USING INDEX idx_orders_customer (customer_id=?)
after: 0.030 ms
The plan changed from SCAN to SEARCH ... USING INDEX, and the time went from 4.391 ms to 0.030 ms on the machine used to write this lesson. Your numbers will differ (they depend on the computer and on what else it is doing), but the pattern, a big drop, will be the same. The answer is identical either way; only the way of finding it changed.
The same thing on the sample data. This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). The timing above needs a big table, so here we compare the plans (a plan is exact; a time depends on the computer). The index you create lives in your browser's copy; Reset data removes it. For EXPLAIN QUERY PLAN the cell shows only the readable plan text.
Find the orders of customer 17 (the orders table has 2,600 rows):
EXPLAIN QUERY PLAN SELECT * FROM orders WHERE customer_id = 17;
SELECT COUNT(*) AS found FROM orders WHERE customer_id = 17;
CREATE INDEX idx_orders_customer ON orders (customer_id);
EXPLAIN QUERY PLAN SELECT * FROM orders WHERE customer_id = 17;
SELECT COUNT(*) AS found FROM orders WHERE customer_id = 17;
plan
-----------
SCAN orders
(1 row)
found
-----
8
(1 row)
plan
-------------------------------------------------------------
SEARCH orders USING INDEX idx_orders_customer (customer_id=?)
(1 row)
found
-----
8
(1 row)
Find the ledger rows of account 17 (the transactions table has 7,415 rows):
EXPLAIN QUERY PLAN SELECT * FROM transactions WHERE account_id = 17;
SELECT COUNT(*) AS found FROM transactions WHERE account_id = 17;
CREATE INDEX idx_txn_account ON transactions (account_id);
EXPLAIN QUERY PLAN SELECT * FROM transactions WHERE account_id = 17;
SELECT COUNT(*) AS found FROM transactions WHERE account_id = 17;
plan
-----------------
SCAN transactions
(1 row)
found
-----
15
(1 row)
plan
--------------------------------------------------------------
SEARCH transactions USING INDEX idx_txn_account (account_id=?)
(1 row)
found
-----
15
(1 row)
Find the submissions of student 17 (the submissions table has 4,087 rows):
EXPLAIN QUERY PLAN SELECT * FROM submissions WHERE student_id = 17;
SELECT COUNT(*) AS found FROM submissions WHERE student_id = 17;
CREATE INDEX idx_sub_student ON submissions (student_id);
EXPLAIN QUERY PLAN SELECT * FROM submissions WHERE student_id = 17;
SELECT COUNT(*) AS found FROM submissions WHERE student_id = 17;
plan
----------------
SCAN submissions
(1 row)
found
-----
7
(1 row)
plan
-------------------------------------------------------------
SEARCH submissions USING INDEX idx_sub_student (student_id=?)
(1 row)
found
-----
7
(1 row)
The plan changed from SCAN (every row) to SEARCH ... USING INDEX, and the number of rows found is the same.
Worked example: is an index worth it?
A school keeps 50,000 student records and staff often look up a student by roll number. Nobody ever searches by the "notes" column.
- Searches by roll number happen all day, and a scan of 50,000 rows each time is wasteful: index
roll_number. - Nobody searches by "notes": an index there would only cost space and time (lesson 7.7): do not index it.
An index helps the columns you search, not every column. The school is made up.
4. The trade-off
An index is not free. It takes disk space, and every time a row is added, changed or deleted, the database must update the index too. So we add indexes where they pay off: columns used often to find rows. Lessons 7.4 and 7.7 show how to choose.
Common mistakes
- Believing an index changes the answer. It never does; only the speed. A query returns the same rows with or without it.
- Adding an index to every column "just in case". Each one slows writes and uses space.
- Trusting a timing from one run. Times vary; read the query plan to know whether an index is used.
- Forgetting small tables do not need them. With a few dozen rows a scan is already instant.
Key takeaways
- Without an index, a query on a column scans every row (
SCAN). - An index is a sorted structure that lets the database jump straight to matching rows (
SEARCH ... USING INDEX). - An index changes speed, never results.
- Indexes cost space and slow down writes, so add them where searches need them.
Practice
1. What does SCAN orders in a query plan tell you?
Show answer
The database is doing a full table scan: it looks at every row of orders.
2. Which part of a book is like a database index?
Show answer
The index at the back: a sorted list of terms with where to find them.
3. After creating the index, did the rows returned by the query change?
Show answer
No. The same 20 rows came back; only the plan and the speed changed.
4. A table has 30 rows. Is an index worth adding?
Show answer
Usually not: scanning 30 rows is already instant, and the index would add maintenance cost.
5. Why can the same query show different times on two runs?
Show answer
Time depends on the computer, other programs running, and caching, so a single timing is not reliable; the query plan is a steadier check.
6. Name a column in a shop's orders table that is worth indexing and say why.
Show answer
For example customer_id: orders are looked up by customer all the time and the column has many different values.