✏️ Explanatory Question

What is an index in MySQL and how does it improve performance?

👁 9 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

Section 7: Indexes & Performance

51

What is an index in MySQL and how does it improve performance?

Level: Advanced — Indexing is the single most important topic for query performance.

An index is a special data structure (usually a B-tree) that stores a sorted copy of one or more columns, allowing MySQL to find rows quickly without scanning the entire table. It works exactly like the index at the back of a book — instead of reading every page, you jump straight to the right one.

The trade-off: Indexes dramatically speed up reads (SELECT) but slow down writes (INSERT/UPDATE/DELETE), because the index must also be updated. They also consume extra disk space.

Why It's So Fast — The Math

A full table scan checks every row, giving linear time complexity:

$$ O(n) \text{ (full table scan)} \quad \text{vs} \quad O(\log n) \text{ (B-tree index lookup)} $$

For a table with 1,000,000 rows, a scan may check a million rows, while a B-tree index needs only about 20 comparisons — a massive difference.

Key Points About Indexes

  • Best on columns used in WHERE, JOIN, ORDER BY, and GROUP BY.
  • A PRIMARY KEY automatically creates a clustered index.
  • Avoid indexing columns with very few distinct values (low selectivity, e.g., gender).
  • Too many indexes hurt write performance and waste space.

With Index vs Without Index

Aspect Without Index With Index
Lookup method Full table scan Direct B-tree seek
Read speed Slow on large tables Very fast
Write speed Faster Slightly slower
Storage Less More (index overhead)

Quick Example

-- Create an index on a frequently searched column
CREATE INDEX idx_lastname ON employees(last_name);

-- Composite index on multiple columns
CREATE INDEX idx_dept_salary ON employees(dept_id, salary);

-- View existing indexes on a table
SHOW INDEX FROM employees;

-- Check whether a query uses an index
EXPLAIN SELECT * FROM employees WHERE last_name = 'Ansari';

-- Drop an index
DROP INDEX idx_lastname ON employees;
Interviewer tip: The one-liner they want — "An index is a B-tree data structure that lets MySQL find rows in O(log n) time instead of an O(n) full scan. It speeds up reads but slows writes and uses extra storage."