A query that scans every row in a million-row table to find 10 results will be slow. An index lets MySQL jump directly to the right rows without scanning. This is the single most impactful optimization you can make to a slow database.
How indexes work
Think of a book index. Instead of reading every page to find "database transactions," you look at the index, find the page number, and go directly there. MySQL's B-tree indexes work the same way.
The most common types
Single-column index: The most basic. Add one when you frequently filter or sort by a single column.
ALTER TABLE users ADD INDEX idx_email (email);
ALTER TABLE orders ADD INDEX idx_status (status);
Composite index: Index multiple columns together. The column order matters — it works for queries that filter on the leftmost columns.
ALTER TABLE orders ADD INDEX idx_user_status (user_id, status);
This index helps queries that filter by user_id alone, or by user_id AND status. It does not help queries that filter by status alone.
In Laravel migrations
$table->index('email');
$table->index(['user_id', 'status']);
$table->unique('email');
$table->fullText('body');
EXPLAIN is your best friend
Before adding indexes blindly, use EXPLAIN to see how MySQL is executing your query:
EXPLAIN SELECT * FROM orders WHERE user_id = 1 AND status = 'pending';
Look at the type column. ALL means a full table scan. ref or range means an index is being used.
What not to index
Do not index every column. Indexes take up disk space and slow down writes. Index the columns you actually filter, sort, or join on. Use EXPLAIN to confirm your indexes are being used.
Also, columns with very low cardinality (like boolean flags) are poor index candidates. MySQL might decide a full table scan is faster.



