Indexes and Performance
Understand how B-tree indexes turn full table scans into quick lookups, choose columns and column order for indexes, and weigh their cost on writes.
Welcome back!
Step 1 of 13Learn
The book index analogy
Looking for "normalization" in a 600-page textbook, you have two options: read every page, or turn to the index at the back, find the entry and jump to page 312. A database faces the same choice. Without help, finding the customer with email ana@example.com means checking every row, a full table scan. With 10 rows that's instant; with 10 million rows, it's slow, and it happens on every login.
An index is a separate, sorted data structure that maps column values to the locations of their rows. With an index on email, the database finds the matching entry quickly and jumps straight to the row.
Primary keys and UNIQUE columns get an index automatically in most systems, because the DBMS needs one to check uniqueness efficiently. Other columns, including foreign keys in many systems, don't, and you add indexes yourself:
CREATE INDEX idx_orders_customer ON orders (customer_id);Indexes are part of physical design. They don't change what a query returns, only how fast it runs, so you can add or drop them at any time without touching the application's logic.
Step 2 of 13Practice · Choose one
A customers table has 5 million rows and no index on email. Users log in by email. What happens on each login lookup?
Step 3 of 13Learn
How a B-tree index works
The most common index structure is the B-tree (in practice usually a variant called a B+ tree). It's a shallow, wide tree of sorted keys.
- The root node holds a few keys that split the value range into sections.
- Internal nodes split each section further.
- Leaf nodes hold every key in sorted order, with a pointer to each row, and are linked to their neighbors.
Each node fits in one disk page and holds hundreds of keys, so the tree's fan-out is large. To find a value, the database reads one node per level, from root to leaf. The number of levels grows with the logarithm of the row count: with a fan-out of 200, three levels cover 2003 = 8 million keys, and four levels cover 1.6 billion. That's why an indexed lookup in a huge table takes only a handful of page reads, compared with reading every page in a scan.
Because leaves are sorted and linked, B-trees also speed up range queries (order_date BETWEEN two dates), sorting (ORDER BY on the indexed column) and prefix searches (name LIKE 'Ana%'). They don't help a search for a value in the middle of a string, such as LIKE '%son', because the sort order is useless when the start of the value is unknown.
Step 4 of 13Try the calculator
Index lookup versus full scan
Levels of a B-tree ≈ log(rows) / log(fan-out), rounded up. A full scan reads every page of the table.
- B-tree levels (page reads per lookup)
- 4
- Pages read by a full table scan
- 200,000
- Scan pages per index page read
- 50,000
Step 5 of 13Practice · Work it out
A B-tree index has a fan-out of 100 keys per node. What is the smallest number of levels that can index 50 million rows?
Step 6 of 13Practice · Chart
B-tree levels as a table grows (fan-out 100)
Every hundredfold increase in rows adds just one level. A full scan, by contrast, grows in direct proportion to the table.
Tap the first size that needs four levels.
Tap the bar that answers the question, then press Check.
Step 7 of 13Learn
Which columns to index
Index the columns your important queries search, join and sort on. Good candidates:
- Foreign keys. Joins and lookups like "orders for customer 12" filter on them constantly. Some systems index them automatically, others (including PostgreSQL) do not.
- Columns in frequent WHERE clauses: email for logins, status for "pending orders," order_date for date ranges.
- Columns in ORDER BY of common, paged lists.
Indexes help most when a condition is selective, picking out a small fraction of rows. An index on a boolean column like is_active, where 95% of rows are true, rarely helps; reading the index and then nearly every row is slower than a plain scan, and the query planner will usually ignore it.
Composite indexes cover several columns, and their order matters. An index on (customer_id, order_date) is sorted by customer first, then by date within each customer, like a phone book sorted by last name, then first name. It serves queries filtering on customer_id alone, or on customer_id and order_date together. It can't efficiently serve a query on order_date alone, just as a phone book can't quickly find everyone with the first name "Maria." This is the leftmost prefix rule: put the column used in equality conditions first, and the range or sort column after it.
Step 8 of 13Practice · Code challenge · SQL
Code challenge · SQL
Queries often look up the orders of one customer (WHERE customer_id = …). Create an index on orders(customer_id). Name it as you like.
The checker lists the indexes you created on orders and the columns they cover.
The database for this exercise (tables and rows)
CREATE TABLE customer (
customer_id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
email TEXT NOT NULL UNIQUE,
city TEXT
);
CREATE TABLE book (
book_id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
price REAL NOT NULL CHECK (price >= 0)
);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
order_date TEXT NOT NULL,
customer_id INTEGER NOT NULL REFERENCES customer (customer_id)
);
CREATE TABLE order_line (
order_id INTEGER NOT NULL REFERENCES orders (order_id),
book_id INTEGER NOT NULL REFERENCES book (book_id),
quantity INTEGER NOT NULL CHECK (quantity > 0),
unit_price REAL NOT NULL,
PRIMARY KEY (order_id, book_id)
);
INSERT INTO customer VALUES
(1, 'Ana Silva', 'ana@example.com', 'Lisbon'),
(2, 'Ben Carter', 'ben@example.com', 'Leeds'),
(3, 'Chen Wei', 'chen@example.com', 'Austin'),
(4, 'Dana Moore', 'dana@example.com', 'Austin');
INSERT INTO book VALUES
(10, 'Designing Data', 39.00),
(11, 'SQL Pocket Guide', 18.50),
(12, 'Keys and Tables', 24.00);
INSERT INTO orders VALUES
(501, '2026-02-01', 1),
(502, '2026-02-03', 2),
(503, '2026-02-10', 1);
INSERT INTO order_line VALUES
(501, 10, 1, 39.00),
(501, 11, 2, 18.50),
(502, 12, 1, 24.00),
(503, 11, 1, 18.50);- Result matches the expected table
Step 9 of 13Practice · Sort into groups
An orders table has one composite index on (customer_id, order_date). Which queries can use it efficiently?
Tap an item, then tap its group (or drag it there).
Step 10 of 13Learn
The cost of indexes
If indexes make reads fast, why not index every column? Because every index has costs:
- Slower writes. Each INSERT must add an entry to every index on the table; each UPDATE of an indexed column must move its entry; each DELETE must remove entries. A table with ten indexes does roughly ten extra pieces of work per insert.
- Storage. Indexes take disk space and memory, sometimes as much as the table itself.
- Maintenance. Indexes can become fragmented and occasionally need rebuilding, and unused ones still cost on every write.
So indexing is a trade-off driven by the workload. A reporting database that's loaded once a night and queried all day can afford many indexes. A table receiving thousands of inserts per second, such as event logs or sensor readings, should have as few as possible.
The professional approach is to measure. Every major DBMS can show its query plan with a command such as EXPLAIN, revealing whether a query uses an index or scans the table and roughly how many rows it touches. Find the slow, frequent queries, add an index targeted at them, and confirm with EXPLAIN that it's used. Periodically look for indexes that are never used and drop them.
Step 11 of 13Note
Step 12 of 13Practice · What would you do?
What would you do?
A logging table receives 5,000 inserts per second and is queried a few times a day by timestamp. A developer proposes indexes on all 12 of its columns "just in case." What is the best response?
Step 13 of 13Practice · Choose one
Which query can NOT be sped up by a standard B-tree index on last_name?
Lesson complete!