++++Use EXPLAIN, indexes, selective filters, and practical query habits to make beginner MySQL queries faster.
19. Query Performance Basics
Query Performance Basics
Correct SQL comes first. After that, performance matters when tables grow and queries start scanning too much data.
Avoid SELECT * in repeated queries
SELECT customer_id, first_name, last_name, email
FROM customers
WHERE country = "USA";Fetching only required columns reduces network transfer and makes the query easier to understand.
Use indexes for common filters
If you often search customers by email, index it.
CREATE INDEX idx_customers_email
ON customers (email);If you often filter and sort by multiple columns, a composite index can help.
CREATE INDEX idx_orders_status_date
ON orders (status, order_date);Column order matters in composite indexes. Put the common filtering columns first.
Read EXPLAIN
EXPLAIN shows how MySQL plans to run a query.
EXPLAIN
SELECT *
FROM orders
WHERE status = "paid"
ORDER BY order_date DESC;Useful fields to notice:
| Field | Meaning |
|---|---|
type | Join/access type. ALL often means a full scan. |
possible_keys | Indexes MySQL could use. |
key | Index MySQL chose. |
rows | Estimated number of rows scanned. |
Extra | Extra work such as filesort or temporary table. |
Write selective WHERE clauses
Specific filters reduce scanned rows.
SELECT *
FROM orders
WHERE status = "paid"
AND order_date >= "2026-01-01";Avoid wrapping indexed columns in functions inside WHERE when possible.
Less index-friendly:
SELECT *
FROM orders
WHERE YEAR(order_date) = 2026;More index-friendly:
SELECT *
FROM orders
WHERE order_date >= "2026-01-01"
AND order_date < "2027-01-01";Index tradeoffs
Indexes speed reads but add storage and write cost. Do not index every column. Index columns that are frequently used for filtering, joining, sorting, or enforcing uniqueness.
Performance work should be measured. Use EXPLAIN before and after changing indexes.