Query Optimization Fundamentals: Functions
Module: Query Optimization & Performance
**Measuring Query Performance:**
```sql
-- PostgreSQL: EXPLAIN ANALYZE shows actual execution time
EXPLAIN ANALYZE
SELECT o.order_id, c.customer_name, o.total_amount
FROM orders o
JOIN customers c ON o.customer_id = c.customer_id
WHERE o.order_date >= '2024-01-01';
-- MySQL: EXPLAIN shows execution plan
EXPLAIN FORMAT=JSON
SELECT o.order_id, c.customer_name, o.total_amount
FROM orders o
JOIN customers c ON o.customer_id = c.customer_id
WHERE o.order_date >= '2024-01-01';
-- SQL Server: Include actual execution plan
SET STATISTICS TIME ON;
SET STATISTICS IO ON;
SELECT o.order_id, c.customer_name, o.total_amount
FROM orders o
JOIN customers c ON o.customer_id = c.customer_id
WHERE o.order_date >= '2024-01-01';
```
**Reading Execution Plans:**
Key metrics to look for:
- **Seq Scan / Table Scan**: Full table scan (bad for large tables)
- **Index Scan**: Using an index (good)
- **Index Seek**: Direct index lookup (best)
- **Nested Loop**: Good for small datasets
- **Hash Join**: Good for large datasets
- **Rows**: Estimated vs actual row counts
- **Cost**: Relative cost estimate
- **Time**: Actual execution time
**Common Plan Patterns:**
```
Good Plan:
-> Index Seek (cost=0.43 rows=10)
-> Nested Loop Join (cost=15.2 rows=10)
-> Index Scan (cost=8.5 rows=100)
Bad Plan:
-> Seq Scan (cost=10000 rows=1000000)