What is an index and how does it speed up queries?

IntermediateConceptMySQL
Answer

Short answer

An index is a separate, sorted data structure (a B-tree in InnoDB) that lets MySQL find rows without scanning the whole table — like the index at the back of a book. It makes reads with WHERE, JOIN and ORDER BY much faster, but uses extra disk space and slightly slows down writes.

Example

-- Without an index on email: scans all 5 million rows
SELECT * FROM customers WHERE email = '[email protected]';

CREATE INDEX idx_customers_email ON customers(email);
-- Now: a few page reads

SHOW INDEX FROM customers;
DROP INDEX idx_customers_email ON customers;

Composite indexes

CREATE INDEX idx_orders_cust_date ON orders(customer_id, created_at);
-- helps: WHERE customer_id = 42 ORDER BY created_at DESC
-- helps: WHERE customer_id = 42
-- doesn't help much: WHERE created_at > '2026-01-01'  (leftmost column missing)

Trade-offs

Benefit Cost
Fast lookups, joins, sorting Extra disk space
Enforces uniqueness (UNIQUE index) Every INSERT/UPDATE/DELETE must update indexes

Checking if a query uses an index

EXPLAIN SELECT * FROM customers WHERE email = '[email protected]';
-- type: ref, key: idx_customers_email   ✅   (type: ALL = full table scan ❌)

What to say in the interview

"An index is a B-tree that lets the engine seek directly to matching rows instead of scanning. I add indexes for frequent WHERE and JOIN columns, respect the leftmost-prefix rule for composite indexes, verify with EXPLAIN, and avoid over-indexing write-heavy tables."

All Databases (MySQL, PostgreSQL, MongoDB) questions Roadmap: MySQL basics

More on MySQL