CHAPTER 27
The single most impactful performance tool available to you.
🌟 Think of it this way: An index on a database column is like the index at the back of a textbook. Without it, to find every mention of 'GROUP BY' you read every page (full table scan). With an index, you jump directly to page 78. The bigger the book, the more dramatic the difference.
SQL
-- Create a standard index CREATE INDEX idx_department ON employees(department); -- Composite index (order matters — most selective column first) CREATE INDEX idx_dept_salary ON employees(department, salary); -- Unique index (also enforces data integrity) CREATE UNIQUE INDEX idx_email ON customers(email); -- Check if index is being used EXPLAIN SELECT * FROM employees WHERE department = 'IT';
| Rule | Explanation |
|---|---|
| Index WHERE columns | Columns in WHERE clauses benefit most from indexes |
| Index JOIN ON columns | Foreign key columns used in JOINs should always be indexed |
| Index ORDER BY columns | Indexes can serve ORDER BY and avoid a sort operation |
| Composite index order | Put the most selective column first (e.g., dept, salary) |
| Do not over-index | Every index slows INSERT/UPDATE/DELETE. Index only what you query |
| EXPLAIN is your friend | Look for type='ALL' (bad) vs 'ref' or 'eq_ref' (good, index used) |
💡 Engineering Insight: At Facebook's scale, adding or removing a single index on a hot table is treated as a high-risk migration requiring a review by a database reliability engineer. A missing index on a 50-billion-row table means queries take minutes instead of milliseconds.