Indexes for
Performance
Learn how database indexes dramatically speed up queries by helping the engine find rows without scanning entire tables.
What Is a Database Index?
An index is a separate data structure the database maintains alongside your table. It stores a sorted copy of one or more columns together with pointers back to the full rows, letting the engine jump straight to matching data instead of reading every row.
Full Scan vs Index Lookup
Why Indexes Matter
The B-Tree: How Indexes Work
Most databases use a B-tree (or B+ tree) for indexes. Data is sorted and split into nodes. At each level, the engine decides which branch to follow: going from root to leaf in just a few hops.
Creating an Index
CREATE INDEX idx_last_name
ON students (last_name);
-- Composite (multi-column) index
CREATE INDEX idx_city_state
ON addresses (city, state);
When WHERE Filters Benefit
WHERE customer_id = 42;
When JOINs Benefit
FROM orders o
JOIN customers c
ON o.customer_id = c.id;
Single vs Composite Indexes
| Single-Column | Composite | |
|---|---|---|
| Columns | One column | Two or more columns |
| Best for | Simple WHERE / JOIN on one column | Multi-column WHERE, covering queries |
| Column order | N/A | Critical: leftmost prefix rule |
| Storage | Less overhead | More overhead |
| Example | INDEX(email) | INDEX(city, state) |
Clustered vs Non-Clustered
How to Decide What to Index
Example: Simple Filter
SELECT * FROM products
WHERE category = 'Electronics';
CREATE INDEX idx_category
ON products (category);
Example: Optimizing a JOIN
FROM students s
JOIN enrollments e
ON s.id = e.student_id
WHERE e.course_id = 101;
Example: ORDER BY and Indexes
WHERE venue_id = 7
ORDER BY event_date DESC
LIMIT 10;
Common Mistakes
Index Cheat Sheet
| Scenario | Index Helps? | Recommended Index |
|---|---|---|
| WHERE col \(=\) value | ✓ Yes | INDEX(col) |
| WHERE col \(>\) value | ✓ Yes | INDEX(col) |
| JOIN ON a.col \(=\) b.col | ✓ Yes | INDEX(b.col) (lookup column) |
| ORDER BY col | ✓ Yes | INDEX(col) or composite |
| WHERE FUNC(col) \(=\) val | ✕ No | Rewrite to avoid function |
| LIKE '%value' | ✕ No | Full-text search instead |
| Low-selectivity col (boolean) | Rarely | Usually not worth it |
Question 1 of 5
A table has 2 million rows. A query uses WHERE email \(=\) 'alice@example.com'. Without an index, how does the database find the row?
Question 2 of 5
You have a composite index on (city, state). Which query can use this index effectively?
Question 3 of 5
A query joins orders and customers on orders.customer_id \(=\) customers.id. Which index most directly speeds up this join?
Question 4 of 5
Why might adding an index on a boolean column (e.g., is_active with values TRUE/FALSE) be a bad idea?
Question 5 of 5
Which of the following is a trade-off of creating too many indexes on a table?