As an application scales from 1,000 users to 10,000,000 records, database performance makes or breaks the user experience. A query that executes in 2 milliseconds on your local laptop can take 45 seconds in production if it is forced to read every disk block sequentially.
An Index is an auxiliary physical data structure maintained on disk that allows the database engine to find specific records in O(log n) time instead of scanning every row in O(n) time.
1. How B+Tree Indexes Work in InnoDB
MySQL's default storage engine, InnoDB, organizes all table data into a B+Tree (Balanced Tree) data structure:
[ Root Node: 50 | 100 ]
/ | / | [ Branch: 10 | 30 ] [ 60 | 80 ] [ 120 | 150 ]
/ | ... ...
┌────────┴───────┴──────┴────────┐
│ Leaf Pages (Linked List) │
│ [1..9] <-> [10..29] <-> [30..49]
└────────────────────────────────┘
Clustered Index vs. Secondary Index
In InnoDB, there is a fundamental architectural distinction between how primary keys and other indexes are stored:
- Clustered Index (Primary Key):
- The primary key is the physical organization of the table.
- The leaf pages of the B+Tree store the actual entire row data (all columns).
- Lookups by Primary Key (
WHERE id = 42) require only 1 tree traversal and retrieve the entire row with zero extra disk lookups.
- Secondary Index (Non-Clustered):
- Any index you create on other columns (e.g.
email,username,status). - The leaf nodes of a secondary index do not store row data; they store the indexed value + the Primary Key pointer.
- Bookmark Lookup (Double Lookup): When you query
WHERE email = 'alice@example.com', MySQL traverses the secondary index to find Alice's PK (id = 1), then traverses the Clustered Index to retrieve the rest of Alice's columns.
2. Types of Indexes in MySQL
A. Single-Column Index
Accelerates lookups filtering on one specific column:
CREATE INDEX idx_users_email ON users(email);
B. Composite (Multi-Column) Index & The Leftmost Prefix Rule
Indexes combining multiple columns for queries that filter by multiple criteria:
CREATE INDEX idx_orders_user_status ON orders(user_id, order_date);
⚠️ THE LEFTMOST PREFIX RULE: A composite index on (A, B, C) can accelerate queries filtering:
WHERE A = ...(YES)WHERE A = ... AND B = ...(YES)WHERE A = ... AND B = ... AND C = ...(YES)WHERE B = ... AND C = ...(NO! Cannot use the index because column A is omitted!)
C. Covering Index (The Ultimate Performance Optimization)
A Covering Index occurs when all columns requested in the SELECT clause exist inside the secondary index itself. When this happens, MySQL satisfies the query entirely from RAM/Index leaf pages, completely bypassing the clustered table disk lookup!
-- If index is: idx_user_lookup(email, username)
SELECT username FROM users WHERE email = 'bob@example.com';
-- EXPLAIN Output: "Using index" (Zero table disk access needed!)
D. Unique Index
Enforces business integrity and speeds up lookups:
CREATE UNIQUE INDEX uq_sku ON products(sku);
3. Query Profiling with EXPLAIN & EXPLAIN ANALYZE
Before shipping any query to production, prepend EXPLAIN to inspect the execution plan calculated by MySQL's query optimizer:
EXPLAIN SELECT * FROM users WHERE email = 'johndoe@example.com';
Key Columns in EXPLAIN Output:
| Column | Meaning | Ideal Values | Warning Values |
|---|---|---|---|
type | Join/Access method | const, eq_ref, ref, range | ALL (Full Table Scan!) |
possible_keys | Candidate indexes evaluated | Lists valid index names | NULL (No indexes available) |
key | The actual index chosen | Specific index name | NULL (Didn't use an index) |
rows | Estimated rows scanned | Low number (e.g., 1-10) | High number (e.g., 5,000,000) |
Extra | Optimization notes | Using index (Covering index) | Using filesort, Using temporary |
4. SARGable Queries & Common Index Traps
A query is SARGable (Search Argument Able) if the database engine can directly exploit an index.
Trap 1: Functions on Indexed Columns (Non-SARGable)
-- ❌ BAD: Wraps indexed column in YEAR() function. Forces a FULL TABLE SCAN!
SELECT * FROM orders WHERE YEAR(order_date) = 2024;
-- ✅ GOOD: Compares raw column against a literal range. Uses B-Tree Index!
SELECT * FROM orders WHERE order_date >= '2024-01-01' AND order_date < '2025-01-01';
Trap 2: Leading Wildcards in LIKE
-- ❌ BAD: Leading wildcard '%smith' cannot binary search the B-Tree! Full scan.
SELECT * FROM users WHERE email LIKE '%@gmail.com';
-- ✅ GOOD: Trailing wildcard 'john%' uses index range scan!
SELECT * FROM users WHERE username LIKE 'john%';
5. The Cost of Indexing
Why not index every column in every table?
- Disk Storage: Indexes are persistent data structures that can easily exceed the size of the raw table data.
- Write Penalty: On every
INSERT,UPDATE, orDELETE, MySQL must recalculate and rebalance the B+Tree nodes for every index on that table. Heavy indexing drastically slows down write-heavy workloads!