MySQL Indexes
MySQL Indexes: Accelerating Queries with B-Tree Lookups
A MySQL index is a sorted lookup structure (typically a B-tree) attached to a table so the database locates matching rows without scanning every record on disk. Adding the right index can turn a multi-second table scan into a sub-millisecond lookup.
How B-Tree Indexes Work
Without an index, MySQL reads rows sequentially from first to last (type: ALL in EXPLAIN). With an index on email, MySQL traverses a balanced tree in just three or four hops directly to the matching row pointer.
flowchart TD
Query["WHERE customer_id = 42"] --> Check{"Index on customer_id?"}
Check -- Yes --> BTree["B-Tree Index Seek (Few Disk Reads)"]
Check -- No --> FullScan["Full Table Scan (Reads Every Row)"]
Practical SQL Example
Create single-column and composite indexes using CREATE INDEX, and inspect query plans with EXPLAIN:
-- Single-column index for fast customer email lookups
CREATE INDEX idx_demo_customers_email
ON demo_customers (email);
-- Composite index: equality column (customer_id) first, range column (created_at) second
CREATE INDEX idx_demo_orders_customer_date
ON demo_orders (customer_id, created_at);
-- Verify that MySQL uses the index
EXPLAIN SELECT id, total_amount, created_at
FROM demo_orders
WHERE customer_id = 42
AND created_at >= '2026-08-01';
Common Mistakes and Best Practices
- Follow the Leftmost Prefix Rule: A composite index on
(customer_id, status, created_at)speeds up queries filtering(customer_id)or(customer_id, status), but cannot help a query filtering only(status)unlesscustomer_idis also supplied. - Avoid Over-Indexing Write-Heavy Tables: Every
INSERT,UPDATE, andDELETEmust update every index on that table. Keep only indexes that real queries use. - Do Not Index Low-Cardinality Booleans Alone: An index on a 50/50
is_activeflag alone rarely beats a table scan; pair it inside a composite index after selective columns if needed.
Frequently Asked Questions
What is a covering index in MySQL?
A covering index contains every column requested by SELECT and WHERE (Using index in EXPLAIN), letting MySQL answer the query from the index without touching the main table rows.
Does a PRIMARY KEY automatically create an index?
Yes, InnoDB physically clusters table rows inside the PRIMARY KEY B-tree index automatically.
How do I inspect existing indexes on a table?
Run SHOW INDEX FROM demo_orders; to list every index name, uniqueness flag, and column sequence.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.