database-optimizer
jeffallan/claude-skills
Optimize PostgreSQL and MySQL queries, indexes, and configuration for measurable performance gains.
What is database-optimizer?
Senior database optimizer that analyzes slow queries, designs index strategies, and tunes configuration across PostgreSQL and MySQL. Use when investigating performance bottlenecks, reading execution plans, or implementing schema optimizations.
- Analyze slow queries and execution plans with EXPLAIN ANALYZE
- Design optimal index strategies including covering indexes
- Tune database configuration parameters for performance
- Optimize schema design and partitioning strategies
- Diagnose and resolve lock contention and deadlocks
- Improve cache hit rates and memory usage
How to install database-optimizer
npx skills add https://github.com/jeffallan/claude-skills --skill database-optimizer- Access to PostgreSQL or MySQL database with query execution permissions
- pg_stat_statements extension enabled (PostgreSQL) or performance_schema enabled (MySQL)
- Ability to run EXPLAIN ANALYZE and create indexes in non-production environment first
How to use database-optimizer
- 1.Capture baseline metrics by running EXPLAIN (ANALYZE, BUFFERS) on the slow query
- 2.Identify bottlenecks in the execution plan (sequential scans, nested loops, low buffer hit ratio)
- 3.Load relevant reference guide (query-optimization.md, index-strategies.md, or database-specific tuning)
- 4.Design optimization strategy (index creation, query rewrite, or config tuning)
- 5.Implement changes incrementally in non-production with CONCURRENTLY flag for indexes
- 6.Re-run EXPLAIN ANALYZE to validate improvement and measure wall-clock time reduction
- 7.Document all changes with before/after metrics and monitoring recommendations
Use cases
- Investigating slow queries by capturing and analyzing EXPLAIN output with buffer statistics
- Designing covering indexes to eliminate heap fetches and improve query selectivity
- Tuning PostgreSQL shared_buffers and work_mem or MySQL performance_schema settings
- Identifying missing indexes on filter columns causing sequential scans
- Comparing before/after execution plans to validate optimization impact
- Database administrators
- Backend engineers optimizing application performance
- DevOps specialists managing database infrastructure
- Performance engineers investigating scalability issues
database-optimizer FAQ
Capture EXPLAIN (ANALYZE, BUFFERS) before creating the index to establish baseline cost and buffer hit ratio. After creating the index with CONCURRENTLY, re-run the same query and compare execution time and cost. Check pg_stat_user_indexes to confirm the index is being used (idx_scan > 0).
EXPLAIN shows the planner's estimated costs and row counts without executing the query. EXPLAIN ANALYZE actually executes the query and shows real execution time, actual row counts, and buffer statistics (hit vs. read). Always use ANALYZE to validate improvements.
Use a covering index (with INCLUDE clause in PostgreSQL) when the query filters on some columns but projects others. A covering index eliminates the need to fetch rows from the heap, reducing I/O. Regular indexes are sufficient if you only need to filter; covering indexes add storage overhead.
Common causes: stale statistics (run ANALYZE after bulk loads), different data distribution, higher concurrency causing lock contention, or insufficient shared_buffers. Always test with production-like data volume and concurrency patterns. Monitor replication lag and write performance after applying changes.
Query pg_stat_user_indexes to see which indexes are actually used (idx_scan > 0). Remove indexes with zero scans. Check for duplicate indexes on the same columns. Use covering indexes strategically to consolidate multiple single-column indexes into one multi-column index.
Full instructions (SKILL.md)
Source of truth, from jeffallan/claude-skills.
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
- Analyze Performance — Capture baseline metrics and run
EXPLAIN ANALYZEbefore 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
ANALYZEafter 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
Related skills
More from jeffallan/claude-skills and the wider catalog.

laravel-specialist
Build Laravel 10+ applications with Eloquent models, Sanctum auth, queues, APIs, and Livewire components.

golang-pro
Senior Go developer for concurrent systems, microservices, and production-grade performance optimization.

flutter-expert
Senior Flutter engineer for cross-platform apps with Riverpod, Bloc, GoRouter, and performance optimization.

php-pro
Senior PHP developer for modern PHP 8.3+, Laravel, Symfony with strict typing, PHPStan level 9, and enterprise patterns.

kubernetes-specialist
Deploy and manage Kubernetes workloads with secure manifests, RBAC, networking, and troubleshooting.

devops-engineer
Creates Dockerfiles, CI/CD pipelines, Kubernetes manifests, and infrastructure-as-code templates for deployment automation.