Indexes & Query Performance
Understand why some queries are slow, how indexes fix that, and the trade-offs every developer needs to know.
An index is like a book index — instead of reading every page, the jumps straight to the answer. Fast reads, slightly slower writes.
EXERCISE
1What is an Index and Why Does It Matter?
An index is a separate data structure that lets MySQL find rows without scanning every row in the table — the difference between finding a word in a book by reading every page vs. using the index at the back.
Without an index — full table scan:
A table with 10 million rows and no index on email:
SELECT * FROM users WHERE email = 'ada@example.com';
-- MySQL reads all 10,000,000 rows one by one to find the match
-- Could take seconds
With an index — direct lookup:
CREATE INDEX idx_email ON users (email);
SELECT * FROM users WHERE email = 'ada@example.com';
-- MySQL jumps directly to the matching rows via the index
-- Takes milliseconds
Creating indexes:
-- Single column index:
CREATE INDEX idx_salary ON employees (salary);
-- Composite index (covers both columns together):
CREATE INDEX idx_dept_salary ON employees (department_id, salary);
-- Unique index (enforces uniqueness AND speeds up lookups):
CREATE UNIQUE INDEX idx_sku ON products (sku);
-- Primary key is automatically indexed — no need to add one
When MySQL uses an index:
-- ✅ Index on salary is used:
WHERE salary > 60000
WHERE salary BETWEEN 50000 AND 80000
ORDER BY salary
-- ❌ Index NOT used (full scan instead):
WHERE YEAR(hire_date) = 2024 -- function on indexed column bypasses index
WHERE salary + 1000 > 60000 -- arithmetic on indexed column
WHERE name LIKE '%ada%' -- leading wildcard kills index
WHERE name LIKE 'ada%' -- ✅ this DOES use the index
Viewing existing indexes:
SHOW INDEXES FROM employees;
-- Shows all indexes, which columns they cover, whether unique
Pro Tip: The most impactful indexes are on columns you frequently use in WHERE, JOIN ON, and ORDER BY clauses. Adding an index on a column that is rarely filtered is just wasted space.
EXERCISE
2Clustered vs Non-Clustered Indexes and the EXPLAIN Plan
Understanding the two types of indexes and how to read an execution plan gives you the tools to diagnose and fix slow queries.
Clustered Index — data is stored in index order:
-- In MySQL InnoDB, the PRIMARY KEY is always the clustered index
-- The actual table rows are physically sorted by the primary key
-- There can only be ONE clustered index per table
CREATE TABLE employees (
id INT AUTO_INCREMENT PRIMARY KEY, -- ← clustered index
name VARCHAR(100)
);
-- Rows on disk: sorted by id. Searching by id is maximally fast.
Non-Clustered Index — separate lookup structure:
-- Any index that is not the primary key is non-clustered
CREATE INDEX idx_name ON employees (name);
-- Separate B-tree of names + pointers back to the main table rows
-- Multiple non-clustered indexes are allowed
Composite index — column order matters:
CREATE INDEX idx_dept_sal ON employees (department_id, salary);
-- This index helps: WHERE department_id = 1
-- This index helps: WHERE department_id = 1 AND salary > 60000
-- This index does NOT help: WHERE salary > 60000 (alone)
-- Rule: the leftmost column(s) must be in the WHERE clause
Reading the EXPLAIN plan:
EXPLAIN SELECT name, salary FROM employees WHERE department_id = 1;
+----+------+-------+---------+------+----------+-------------+
| id | type | table | key | rows | filtered | Extra |
+----+------+-------+---------+------+----------+-------------+
| 1 | ref | empl |idx_dept | 12 | 100.00 | Using index |
+----+------+-------+---------+------+----------+-------------+
type = 'ref' → good (using an index)
type = 'ALL' → bad (full table scan — needs an index)
key → which index was used (NULL = no index)
rows → estimated rows examined (lower is better)
Pro Tip: Run
EXPLAINbefore any query you are trying to optimise. The single most impactful thing to look for:type = 'ALL'with a largerowsnumber. That is your slow query, and adding the right index fixes it.
EXERCISE
3Query Optimisation Best Practices
Fast queries are not luck — they follow predictable patterns. These are the rules that the most experienced SQL writers apply automatically.
Rule 1 — Never SELECT * in production:
-- ❌ Fetches all columns including large TEXT/BLOB fields:
SELECT * FROM products WHERE category = 'Electronics';
-- ✅ Fetch only what you need:
SELECT id, name, price FROM products WHERE category = 'Electronics';
-- Less data transferred, index covering more likely, faster always
Rule 2 — Filter early with WHERE before GROUP BY:
-- ✅ WHERE eliminates rows before grouping (processes less data):
SELECT department, COUNT(*) FROM employees
WHERE status = 'active' -- ← reduce rows first
GROUP BY department;
Rule 3 — Avoid functions on indexed columns in WHERE:
-- ❌ YEAR() on hire_date prevents index use:
WHERE YEAR(hire_date) = 2024
-- ✅ Range condition uses the index:
WHERE hire_date >= '2024-01-01' AND hire_date < '2025-01-01'
Rule 4 — Use EXISTS instead of IN for large subqueries:
-- ❌ IN loads entire subquery result into memory:
WHERE customer_id IN (SELECT id FROM customers WHERE city = 'Mumbai')
-- ✅ EXISTS stops at first match:
WHERE EXISTS (SELECT 1 FROM customers c WHERE c.id = o.customer_id AND c.city = 'Mumbai')
Rule 5 — LIMIT early when possible:
-- If you only need the top result, say so immediately:
SELECT name FROM employees ORDER BY salary DESC LIMIT 1;
-- MySQL can stop after finding the first row instead of sorting all rows
Rule 6 — Use covering indexes for frequent queries:
-- If you always query name + salary together, cover both:
CREATE INDEX idx_name_salary ON employees (name, salary);
-- MySQL never needs to touch the main table — all data is in the index
Pro Tip: The biggest performance gains come from: (1) adding the right indexes, (2) avoiding functions on indexed columns in WHERE, (3) selecting only needed columns. These three changes fix 90% of slow queries.
