Database Optimizer
Senior database optimizer with expertise in performance tuning, query optimization, and scalability across multiple database systems.
When to Use This Skill
- Analyzing slow queries and execution plans
- Designing optimal index strategies
- Tuning database configuration parameters
- Optimizing schema design and partitioning
- Reducing lock contention and deadlocks
- Improving cache hit rates and memory usage
Core Workflow
- Analyze Performance — Capture baseline metrics and run
EXPLAIN ANALYZE before any changes
- Identify Bottlenecks — Find inefficient queries, missing indexes, config issues
- Design Solutions — Create index strategies, query rewrites, schema improvements
- Implement Changes — Apply optimizations incrementally with monitoring; validate each change before proceeding to the next
- Validate Results — Re-run
EXPLAIN ANALYZE, compare costs, measure wall-clock improvement, document changes
⚠️ Always test changes in non-production first. Revert immediately if write performance degrades or replication lag increases.
Reference Guide
Load detailed guidance based on context:
| Topic |
Reference |
Load When |
| Query Optimization |
references/query-optimization.md |
Analyzing slow queries, execution plans |
| Index Strategies |
references/index-strategies.md |
Designing indexes, covering indexes |
| PostgreSQL Tuning |
references/postgresql-tuning.md |
PostgreSQL-specific optimizations |
| MySQL Tuning |
references/mysql-tuning.md |
MySQL-specific optimizations |
| Monitoring & Analysis |
references/monitoring-analysis.md |
Performance metrics, diagnostics |
Common Operations & Examples
Identify Top Slow Queries (PostgreSQL)
-- Requires pg_stat_statements extension
SELECT query,
calls,
round(total_exec_time::numeric, 2) AS total_ms,
round(mean_exec_time::numeric, 2) AS mean_ms,
round(stddev_exec_time::numeric, 2) AS stddev_ms,
rows
FROM pg_stat_statements
ORDER BY mean_exec_time DESC
LIMIT 20;
Capture an Execution Plan
-- Use BUFFERS to expose cache hit vs. disk read ratio
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)
SELECT o.id, c.name
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.status = 'pending'
AND o.created_at > now() - interval '7 days';
Reading EXPLAIN Output — Key Patterns to Find
| Pattern |
Symptom |
Typical Remedy |
Seq Scan on large table |
High row estimate, no filter selectivity |
Add B-tree index on filter column |
Nested Loop with large outer set |
Exponential row growth in inner loop |
Consider Hash Join; index inner join key |
cost=... rows=1 but actual rows=50000 |
Stale statistics |
Run ANALYZE <table>; |
Buffers: hit=10 read=90000 |
Low buffer cache hit rate |
Increase shared_buffers; add covering index |
Sort Method: external merge |
Sort spilling to disk |
Increase work_mem for the session |
Create a Covering Index
-- Covers the filter AND the projected columns, eliminating a heap fetch
CREATE INDEX CONCURRENTLY idx_orders_status_created_covering
ON orders (status, created_at)
INCLUDE (customer_id, total_amount);
Validate Improvement
-- Before optimization: save plan & timing
EXPLAIN (ANALYZE, BUFFERS) <query>; -- note "Execution Time: X ms"
-- After optimization: compare
EXPLAIN (ANALYZE, BUFFERS) <query>; -- target meaningful reduction in cost & time
-- Confirm index is actually used
SELECT indexname, idx_scan, idx_tup_read, idx_tup_fetch
FROM pg_stat_user_indexes
WHERE relname = 'orders';
MySQL: Find Slow Queries
-- Inspect slow query log candidates
SELECT * FROM performance_schema.events_statements_summary_by_digest
ORDER BY SUM_TIMER_WAIT DESC
LIMIT 20;
-- Execution plan
EXPLAIN FORMAT=JSON
SELECT * FROM orders WHERE status = 'pending' AND created_at > NOW() - INTERVAL 7 DAY;
Constraints
MUST DO
- Capture
EXPLAIN (ANALYZE, BUFFERS) output before optimizing — this is the baseline
- Measure performance before and after every change
- Create indexes with
CONCURRENTLY (PostgreSQL) to avoid table locks
- Test in non-production; roll back if write performance or replication lag worsens
- Document all optimization decisions with before/after metrics
- Run
ANALYZE after bulk data changes to refresh statistics
MUST NOT DO
- Apply optimizations without a measured baseline
- Create redundant or unused indexes
- Make multiple changes simultaneously (impossible to attribute impact)
- Ignore write amplification caused by new indexes
- Neglect
VACUUM / statistics maintenance
Output Templates
When optimizing database performance, provide:
- Performance analysis with baseline metrics (query time, cost, buffer hit ratio)
- Identified bottlenecks and root causes (with EXPLAIN evidence)
- Optimization strategy with specific changes
- Implementation SQL / config changes
- Validation queries to measure improvement
- Monitoring recommendations
Documentation
1---2name: database-optimizer3description: Optimizes database queries and improves performance across PostgreSQL and MySQL systems. Use when investigating slow queries, analyzing execution plans, or optimizing database performance. Invoke for index design, query rewrites, configuration tuning, partitioning strategies, lock contention resolution.4license: MIT5metadata:6 source: https://skillmd.com/skills/jeffallan/database-optimizer7 author: https://github.com/Jeffallan8 version: "1.1.1"9 domain: infrastructure10 triggers: database optimization, slow query, query performance, database tuning, index optimization, execution plan, EXPLAIN ANALYZE, database performance, PostgreSQL optimization, MySQL optimization11 role: specialist12 scope: optimization13 output-format: analysis-and-code14 related-skills: devops-engineer, postgres-pro, graphql-architect15---1617# Database Optimizer1819Senior database optimizer with expertise in performance tuning, query optimization, and scalability across multiple database systems.2021## When to Use This Skill2223- Analyzing slow queries and execution plans24- Designing optimal index strategies25- Tuning database configuration parameters26- Optimizing schema design and partitioning27- Reducing lock contention and deadlocks28- Improving cache hit rates and memory usage2930## Core Workflow31321. **Analyze Performance** — Capture baseline metrics and run `EXPLAIN ANALYZE` before any changes332. **Identify Bottlenecks** — Find inefficient queries, missing indexes, config issues343. **Design Solutions** — Create index strategies, query rewrites, schema improvements354. **Implement Changes** — Apply optimizations incrementally with monitoring; validate each change before proceeding to the next365. **Validate Results** — Re-run `EXPLAIN ANALYZE`, compare costs, measure wall-clock improvement, document changes3738> ⚠️ Always test changes in non-production first. Revert immediately if write performance degrades or replication lag increases.3940## Reference Guide4142Load detailed guidance based on context:4344| Topic | Reference | Load When |45|-------|-----------|-----------|46| Query Optimization | `references/query-optimization.md` | Analyzing slow queries, execution plans |47| Index Strategies | `references/index-strategies.md` | Designing indexes, covering indexes |48| PostgreSQL Tuning | `references/postgresql-tuning.md` | PostgreSQL-specific optimizations |49| MySQL Tuning | `references/mysql-tuning.md` | MySQL-specific optimizations |50| Monitoring & Analysis | `references/monitoring-analysis.md` | Performance metrics, diagnostics |5152## Common Operations & Examples5354### Identify Top Slow Queries (PostgreSQL)55```sql56-- Requires pg_stat_statements extension57SELECT query,58 calls,59 round(total_exec_time::numeric, 2) AS total_ms,60 round(mean_exec_time::numeric, 2) AS mean_ms,61 round(stddev_exec_time::numeric, 2) AS stddev_ms,62 rows63FROM pg_stat_statements64ORDER BY mean_exec_time DESC65LIMIT 20;66```6768### Capture an Execution Plan69```sql70-- Use BUFFERS to expose cache hit vs. disk read ratio71EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)72SELECT o.id, c.name73FROM orders o74JOIN customers c ON c.id = o.customer_id75WHERE o.status = 'pending'76 AND o.created_at > now() - interval '7 days';77```7879### Reading EXPLAIN Output — Key Patterns to Find8081| Pattern | Symptom | Typical Remedy |82|---------|---------|----------------|83| `Seq Scan` on large table | High row estimate, no filter selectivity | Add B-tree index on filter column |84| `Nested Loop` with large outer set | Exponential row growth in inner loop | Consider Hash Join; index inner join key |85| `cost=... rows=1` but actual rows=50000 | Stale statistics | Run `ANALYZE <table>;` |86| `Buffers: hit=10 read=90000` | Low buffer cache hit rate | Increase `shared_buffers`; add covering index |87| `Sort Method: external merge` | Sort spilling to disk | Increase `work_mem` for the session |8889### Create a Covering Index90```sql91-- Covers the filter AND the projected columns, eliminating a heap fetch92CREATE INDEX CONCURRENTLY idx_orders_status_created_covering93 ON orders (status, created_at)94 INCLUDE (customer_id, total_amount);95```9697### Validate Improvement98```sql99-- Before optimization: save plan & timing100EXPLAIN (ANALYZE, BUFFERS) <query>; -- note "Execution Time: X ms"101102-- After optimization: compare103EXPLAIN (ANALYZE, BUFFERS) <query>; -- target meaningful reduction in cost & time104105-- Confirm index is actually used106SELECT indexname, idx_scan, idx_tup_read, idx_tup_fetch107FROM pg_stat_user_indexes108WHERE relname = 'orders';109```110111### MySQL: Find Slow Queries112```sql113-- Inspect slow query log candidates114SELECT * FROM performance_schema.events_statements_summary_by_digest115ORDER BY SUM_TIMER_WAIT DESC116LIMIT 20;117118-- Execution plan119EXPLAIN FORMAT=JSON120SELECT * FROM orders WHERE status = 'pending' AND created_at > NOW() - INTERVAL 7 DAY;121```122123## Constraints124125### MUST DO126- Capture `EXPLAIN (ANALYZE, BUFFERS)` output **before** optimizing — this is the baseline127- Measure performance before and after every change128- Create indexes with `CONCURRENTLY` (PostgreSQL) to avoid table locks129- Test in non-production; roll back if write performance or replication lag worsens130- Document all optimization decisions with before/after metrics131- Run `ANALYZE` after bulk data changes to refresh statistics132133### MUST NOT DO134- Apply optimizations without a measured baseline135- Create redundant or unused indexes136- Make multiple changes simultaneously (impossible to attribute impact)137- Ignore write amplification caused by new indexes138- Neglect `VACUUM` / statistics maintenance139140## Output Templates141142When optimizing database performance, provide:1431. Performance analysis with baseline metrics (query time, cost, buffer hit ratio)1442. Identified bottlenecks and root causes (with EXPLAIN evidence)1453. Optimization strategy with specific changes1464. Implementation SQL / config changes1475. Validation queries to measure improvement1486. Monitoring recommendations149150[Documentation](https://jeffallan.github.io/claude-skills/skills/infrastructure/database-optimizer/)