Introduction to Query Optimization
The Slowdown
As our data grew, my queries got slower. What used to take 1 second now took 60. It was time to learn *optimization*.
The Mindset
Optimization is about understanding how the database *executes* your query, not just what the query *says*.
Key Concepts
1. **Execution Plan**: The database's internal plan for running your query.
2. **Indexes**: Pre-built shortcuts for finding data.
3. **I/O Cost**: How much data does the database have to read?
4. **Memory/Sort Cost**: How much data has to be held in memory?
The Tool: EXPLAIN
EXPLAIN ANALYZE SELECT * FROM orders WHERE customer_id = 100;
This shows you the database's plan: Is it scanning the whole table? Using an index?
Pro Tip
Never optimize blindly. Always measure first with `EXPLAIN ANALYZE`.
*Day 72: Understanding the EXPLAIN Output.*