MySQL
Query Optimization
Diagnose and optimize slow queries with EXPLAIN and indexes.
By EZ4Code Team
optimizationperformanceexplain
Code
-- 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;Explanation
EXPLAIN reveals the access method (const, ref, range, scan) and indexes MySQL plans to use. Composite indexes that cover WHERE, JOIN, and ORDER BY columns let MySQL serve a query from the index alone, avoiding table lookups. Enable the slow query log to identify queries worth optimizing.
More MySQL Snippets
SELECT with JOINs
Combine rows from multiple tables using JOINs.
Subqueries
Use scalar, IN, EXISTS, and derived-table subqueries.
Indexes
Create single, composite, unique, and fulltext indexes.
Transactions
Use BEGIN, COMMIT, ROLLBACK, and isolation levels.
Stored Procedures
Define reusable procedural routines with parameters.
Triggers
Run logic automatically on INSERT, UPDATE, or DELETE.