Skip to content
MySQL

Query Optimization

Diagnose and optimize slow queries with EXPLAIN and indexes.

#optimization#performance#explain

Code

mysql
-- Inspect the execution plan
EXPLAIN FORMAT=JSON
SELECT * FROM orders WHERE customer_id = 7 ORDER BY created_at;

-- Avoid SELECT *; project only needed columns
SELECT id, total FROM orders WHERE customer_id = 7;

-- Composite index covering WHERE and ORDER BY
CREATE INDEX idx_cust_created ON orders(customer_id, created_at);

-- Covering index includes selected columns
CREATE INDEX idx_cust_total ON orders(customer_id, total);

-- Find slow queries (enable first)
SHOW VARIABLES LIKE 'slow_query_log%';
SET GLOBAL slow_query_log = 'ON';
SET GLOBAL long_query_time = 1;

-- Analyze table for stats refresh
ANALYZE TABLE orders;