Labs ICT
⭐ Pro Login

Query Optimization

How the database engine makes your queries faster.

How the Database Engine Thinks

When you write a query, the database doesn't just execute it blindly. The query optimizer analyzes the query and finds the most efficient way to execute it. Understanding this process helps you write faster queries.

Query Execution Steps


  1. Parse      β†’ Check SQL syntax, build parse tree
  2. Validate   β†’ Check table/column names, permissions
  3. Optimize   β†’ Choose best execution plan (uses indexes? joins order?)
  4. Execute    β†’ Run the chosen plan
  5. Return     β†’ Send results to client

EXPLAIN: See the Plan


  EXPLAIN SELECT * FROM Students WHERE Name = 'Alice';

  β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
  β”‚ id  β”‚ select_type β”‚ table β”‚ type                 β”‚
  β”œβ”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
  β”‚ 1   β”‚ SIMPLE      β”‚Studentsβ”‚ ALL (full scan)      β”‚
  β””β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

  After adding index:
  β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
  β”‚ id  β”‚ select_type β”‚ table β”‚ type                 β”‚
  β”œβ”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
  β”‚ 1   β”‚ SIMPLE      β”‚Studentsβ”‚ ref (index lookup)   β”‚
  β””β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Common Optimization Tips

  • Use indexes on columns in WHERE, JOIN, and ORDER BY.
  • Avoid SELECT * β€” only select the columns you need.
  • Use JOIN instead of subqueries when possible.
  • Filter early β€” use WHERE before GROUP BY.
  • Avoid functions on indexed columns β€” WHERE YEAR(Date) = 2024 can't use an index on Date.
  • Use appropriate data types β€” INT is faster than VARCHAR for numeric IDs.

πŸ§ͺ Quick Quiz

What does EXPLAIN do in SQL?