✏️ Explanatory Question

How do you optimize a slow query in MySQL?

👁 5 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

56

How do you optimize a slow query in MySQL?

Level: Advanced — An open-ended favourite; interviewers want a structured, practical checklist.

Query optimization is a systematic process of finding why a query is slow and then removing the bottleneck. The best answer follows a clear methodology rather than random tweaks.

Step-by-Step Optimization Checklist

  • 1. Analyze with EXPLAIN: Identify full table scans (type=ALL), missing indexes (key=NULL), and high row counts.
  • 2. Add proper indexes: On columns in WHERE, JOIN, ORDER BY, and GROUP BY.
  • 3. Avoid SELECT *: Fetch only the columns you need to reduce I/O and enable covering indexes.
  • 4. Don't wrap indexed columns in functions: WHERE YEAR(date)=2026 blocks the index; use a range instead.
  • 5. Rewrite correlated subqueries as JOINs: Joins are usually optimized better.
  • 6. Filter early: Use WHERE to reduce rows before grouping/joining.
  • 7. Use LIMIT and keyset pagination: Avoid large offsets on deep pages.
  • 8. Keep statistics fresh: Run ANALYZE TABLE so the optimizer has accurate data.
The #1 rule: Never put an indexed column inside a function or expression in the WHERE clause. It forces MySQL to evaluate every row, defeating the index entirely.

Good vs Bad Patterns

Bad (index blocked)

  • WHERE YEAR(order_date) = 2026
  • WHERE status != 'X' (negation)
  • SELECT * everywhere
  • LIKE '%text' (leading wildcard)

Good (index-friendly)

  • WHERE order_date >= '2026-01-01'
  • WHERE status = 'Active'
  • SELECT id, name
  • LIKE 'text%' (trailing wildcard)

Quick Example — Optimizing a Query

-- BEFORE: function on column blocks the index (full scan)
SELECT * FROM orders WHERE YEAR(order_date) = 2026;

-- AFTER: sargable range condition uses the index
SELECT id, customer_id, amount
FROM orders
WHERE order_date >= '2026-01-01'
  AND order_date <  '2027-01-01';

-- Add a supporting index
CREATE INDEX idx_order_date ON orders(order_date);

-- Refresh optimizer statistics
ANALYZE TABLE orders;

-- Confirm the improvement
EXPLAIN SELECT id FROM orders
WHERE order_date >= '2026-01-01';
Term to know — "sargable": A condition is sargable (Search ARGument ABLE) if it can use an index. Rewriting non-sargable predicates into sargable ones is the heart of query tuning.
Interviewer tip: Structure your answer — start with EXPLAIN, then add indexes, avoid SELECT * and functions on indexed columns, rewrite subqueries as joins, and keep statistics updated. A methodical answer beats a random list of tips.