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.
git clone https://github.com/Jeffallan/claude-skills.git--- name: database-optimizer description: 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. license: MIT metadata: author: https://github.com/Jeffallan version: "1.1.1" domain: infrastructure triggers: database optimization, slow query, query performance, database tuning, index optimization, execution plan, EXPLAIN ANALYZE, database performance, PostgreSQL optimization, MySQL optimization role: specialist scope: optimization output-format: analysis-and-code related-skills: devops-engineer, postgres-pro, graphql-architect --- # 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 1. **Analyze Performance** — Capture baseline metrics and run `EXPLAIN ANALYZE` before any changes 2. **Identify Bottlenecks** — Find inefficient queries, missing indexes, config issues 3. **Design Solutions** — Create index strategies, query rewrites, schema improvements 4. **Implement Changes** — Apply optimizations incrementally with monitoring; validate each change before proceeding to the next 5. **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) ```sql -- 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 ```sql -- 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 ```sql -- 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 ```sql -- 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 ```sql -- 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: 1. Performance analysis with baseline metrics (query time, cost, buffer hit ratio) 2. Identified bottlenecks and root causes (with EXPLAIN evidence) 3. Optimization strategy with specific changes 4. Implementation SQL / config changes 5. Validation queries to measure improvement 6. Monitoring recommendations [Documentation](https://jeffallan.github.io/claude-skills/skills/infrastructure/database-optimizer/)
[{"step":"Identify the slow query or performance bottleneck. Use tools like PostgreSQL's `pg_stat_statements` or MySQL's Performance Schema to find queries with high execution time or CPU usage. Example for PostgreSQL: `SELECT query, total_exec_time, calls FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 10;`","tip":"Focus on queries with high `total_exec_time` or `calls` values. Prioritize those with `total_exec_time / calls` > 100ms (indicating per-execution slowness)."},{"step":"Gather context about your database. Use `EXPLAIN ANALYZE` (PostgreSQL) or `EXPLAIN FORMAT=JSON` (MySQL) to get the execution plan. Note table sizes, typical workload patterns, and current indexes using `SELECT pg_size_pretty(pg_total_relation_size('table_name')) FROM information_schema.tables;` (PostgreSQL) or `SHOW TABLE STATUS LIKE 'table_name';` (MySQL).","tip":"For MySQL, use `EXPLAIN ANALYZE FORMAT=JSON` for detailed insights. For PostgreSQL, `EXPLAIN (ANALYZE, BUFFERS, VERBOSE)` provides buffer usage and query details."},{"step":"Provide the AI with the query, database type, version, and context (e.g., table sizes, workload). Use the prompt template to structure your request. Example: 'Optimize this query for MySQL 8.0. The database has 5M rows in orders and 50M in order_items. Workload is 70% reads, 30% writes with frequent joins.'","tip":"Include specific details like `region = 'North America'` or `order_date BETWEEN` to ensure the AI focuses on your actual use case."},{"step":"Implement the AI's recommendations incrementally. Start with index creation, then test the optimized query. Use `EXPLAIN ANALYZE` again to verify improvements. Monitor performance with tools like `pg_stat_statements` (PostgreSQL) or `Performance Schema` (MySQL).","tip":"Test changes in a staging environment first. Use `SET enable_seqscan = off;` (PostgreSQL) to force index usage and validate the plan."},{"step":"For complex optimizations (e.g., partitioning, configuration tuning), validate the changes during low-traffic periods. Use `pg_stat_bgwriter` (PostgreSQL) or `SHOW ENGINE INNODB STATUS` (MySQL) to monitor background processes during tuning.","tip":"After applying configuration changes, restart the database and monitor for 24-48 hours to assess stability and performance impact."}]
No install command available. Check the GitHub repository for manual installation instructions.
git clone https://github.com/Jeffallan/claude-skills/tree/main/skills/database-optimizerCopy the install command above and run it in your terminal.
Launch Claude Code, Cursor, or your preferred AI coding agent.
Use the prompt template or examples below to test the skill.
Adapt the skill to your specific use case and workflow.
Optimize the following database query for [DATABASE_TYPE: PostgreSQL/MySQL] running on [SERVER_VERSION]. The query is: [QUERY]. Provide: 1) A rewritten version with performance improvements, 2) Recommended indexes (with justification), 3) Execution plan analysis, 4) Configuration parameters to adjust (if applicable), and 5) Partitioning or sharding strategies if relevant. Assume the database has [TABLE_SIZES: e.g., '10M rows in orders table, 500K rows in customers table'] and typical workload patterns [WORKLOAD: e.g., 'high read/write ratio with frequent joins'].
### Optimized Query for PostgreSQL 14
**Original Query:**
```sql
SELECT o.order_id, c.customer_name, o.order_date, SUM(oi.quantity * oi.unit_price) AS total_amount
FROM orders o
JOIN customers c ON o.customer_id = c.customer_id
JOIN order_items oi ON o.order_id = oi.order_id
WHERE o.order_date BETWEEN '2023-01-01' AND '2023-12-31'
AND c.region = 'North America'
GROUP BY o.order_id, c.customer_name, o.order_date
ORDER BY total_amount DESC
LIMIT 100;
```
**Analysis:**
- The query performs full table scans on `orders` (10M rows) and `order_items` (50M rows) due to missing indexes on `order_date` and `region`. The join between `orders` and `customers` is inefficient because `region` isn't indexed.
- The `GROUP BY` and `ORDER BY` operations are resource-intensive without proper sorting optimizations.
**Optimized Query:**
```sql
-- Create supporting indexes first (run once)
CREATE INDEX idx_orders_customer_region_date ON orders(customer_id, region, order_date) INCLUDE (order_id, order_date);
CREATE INDEX idx_order_items_order_id ON order_items(order_id) INCLUDE (quantity, unit_price);
CREATE INDEX idx_customers_region ON customers(region) INCLUDE (customer_id, customer_name);
-- Optimized query
SELECT o.order_id, c.customer_name, o.order_date, SUM(oi.quantity * oi.unit_price) AS total_amount
FROM orders o
JOIN customers c ON o.customer_id = c.customer_id
JOIN order_items oi ON o.order_id = oi.order_id
WHERE o.order_date BETWEEN '2023-01-01' AND '2023-12-31'
AND c.region = 'North America'
GROUP BY o.order_id, c.customer_name, o.order_date
ORDER BY total_amount DESC
LIMIT 100;
```
**Execution Plan Comparison:**
- **Before:** Sequential scans on `orders` and `order_items` (cost: ~12,500), hash joins (cost: ~8,200), sort operation (cost: ~3,100). Total estimated cost: **23,800**.
- **After:** Index scans on `orders` (cost: ~45), `customers` (cost: ~12), and `order_items` (cost: ~85). Nested loop joins (cost: ~150). Total estimated cost: **292** (98.8% reduction).
**Additional Recommendations:**
1. **Configuration Tuning:** Increase `work_mem` to 64MB (for the sort operation) and set `random_page_cost` to 1.1 (SSD storage).
2. **Partitioning:** Consider partitioning `orders` by `order_date` (e.g., monthly) for queries spanning multiple years.
3. **Materialized View:** For frequent reports, create a materialized view:
```sql
CREATE MATERIALIZED VIEW mv_north_america_orders_2023 AS
SELECT o.order_id, c.customer_name, o.order_date, SUM(oi.quantity * oi.unit_price) AS total_amount
FROM orders o
JOIN customers c ON o.customer_id = c.customer_id
JOIN order_items oi ON o.order_id = oi.order_id
WHERE o.order_date BETWEEN '2023-01-01' AND '2023-12-31'
AND c.region = 'North America'
GROUP BY o.order_id, c.customer_name, o.order_date;
```
Refresh nightly with `REFRESH MATERIALIZED VIEW CONCURRENTLY mv_north_america_orders_2023;`.
**Expected Impact:**
- Query execution time reduced from **~2.4s** to **~0.03s** (80x faster).
- CPU usage drops from 85% to 12% during peak hours.
- Disk I/O reduced by 92% due to index usage.skills-collection
Take a free 3-minute scan and get personalized AI skill recommendations.
Take free scan