01 / 21

Indexes for
Performance

Learn how database indexes dramatically speed up queries by helping the engine find rows without scanning entire tables.

SQL

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

Full Table Scan Row 1 ✕ Row 2 ✕ Row 3 ✕ Row 4 ✓ Match! Row 5 ✕ ... checks every row Reads N rows Index Lookup Root A-M N-Z Row 4 ✓ Full Row Data
Reads \(\approx \log N\) rows

Why Indexes Matter

Speed
Queries that filter or join on indexed columns can be orders of magnitude faster: from seconds to milliseconds.
Scale
Tables with millions of rows become manageable. Without indexes, performance degrades linearly with table size.
Trade-off
Indexes use extra disk space and slow down INSERT/UPDATE/DELETE because the index must be maintained.

The B-Tree: How Indexes Work

50 ROOT 20 | 35 70 | 85 5, 10, 15 22, 28 38, 42 55, 60 72, 78 88, 92 LEAF NODES point to actual table rows Find 28: Root → 20|35 → [22,28] ✓

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

-- Single-column 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

SELECT * FROM orders
WHERE customer_id = 42;
1
Equality checks (\(=\)): The most common and efficient use of an index. The engine navigates the B-tree directly.
2
Range queries (\(>\), \(<\), BETWEEN): The index finds the start point and scans forward through sorted leaves.
3
Prefix LIKE ('abc%'): Works because sorted order lets the engine seek to 'abc'. But LIKE '%abc' cannot use the index.

When JOINs Benefit

SELECT o.id, c.name
FROM orders o
JOIN customers c
  ON o.customer_id = c.id;
orders id customer_id 1 42 2 17 3 42 4 8 INDEX ON customers(id) customers id name 8 Alice 17 Bob 42 Carol

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

Clustered Index
Determines the physical order of rows on disk. Only one per table. Usually the primary key. The table IS the index.
Non-Clustered Index
A separate structure with pointers back to the actual rows. You can have many per table. Created with CREATE INDEX.

How to Decide What to Index

1
Identify slow queries. Look at queries with WHERE, JOIN, or ORDER BY clauses that touch large tables.
2
Check the columns in filters and joins. These are your index candidates: the columns the engine needs to search.
3
Consider selectivity. High-selectivity columns (many unique values like email) benefit more than low-selectivity columns (like boolean flags).
4
Weigh the cost. Every index slows writes and uses storage. Only index columns your queries actually need.
5
Use EXPLAIN. Run EXPLAIN on your query to verify the database actually uses the index you created.

Example: Simple Filter

-- Slow: full table scan on 500K rows
SELECT * FROM products
WHERE category = 'Electronics';
-- Fix: create an index on the filter column
CREATE INDEX idx_category
ON products (category);

Example: Optimizing a JOIN

SELECT s.name, e.grade
FROM students s
JOIN enrollments e
  ON s.id = e.student_id
WHERE e.course_id = 101;
1
Index on enrollments(course_id): speeds up the WHERE filter to find enrollments in course 101.
2
Index on students(id): typically the primary key, so it already has a clustered index. The JOIN lookup is fast.
3
Even better: composite index on enrollments(course_id, student_id) covers both the filter and the join column in one lookup.

Example: ORDER BY and Indexes

SELECT * FROM events
WHERE venue_id = 7
ORDER BY event_date DESC
LIMIT 10;

Common Mistakes

✕ Indexing Everything
Adding indexes on every column wastes storage and slows down all INSERT, UPDATE, and DELETE operations.
✕ Wrong Column Order
A composite index on (state, city) won't help a query that filters only on city. The leftmost prefix rule applies.
✕ Functions on Indexed Columns
Writing WHERE UPPER(name) = 'ALICE' prevents the index on name from being used. The function wraps the column.

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?