Skip to main content
skill Claude Code CX Codex Cursor GitHub Copilot

database-optimizer — Claude Code skill: what it does, how to install

Investigates slow PostgreSQL and MySQL queries, breaks down execution plans with EXPLAIN ANALYZE, and drafts indexes without table locks.

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add Jeffallan/claude-skills --skill database-optimizer -a claude-code
Open on GitHub

What database-optimizer does

This skill guides database tuning through a strict five-step routine. The agent starts by running EXPLAIN (ANALYZE, BUFFERS) to record baseline query costs and buffer cache hits. It flags inefficient patterns such as sequential scans on massive tables or sorts spilling to disk.

Under the hood, reference guides supply tuning rules for PostgreSQL and MySQL. The workflow uses pg_stat_statements to extract top slow queries in Postgres and performance_schema tables in MySQL. Index creation in PostgreSQL enforces CONCURRENTLY to prevent blocking active application writes.

A firm rule forbids applying fixes without a measured baseline. Changes require testing in staging first. If write performance drops or replication lag rises after applying an index, the changes must be reverted right away.

What it helps with

  • Isolate the slowest database queries using pg_stat_statements or performance_schema
  • Analyze EXPLAIN (ANALYZE, BUFFERS) output to detect cache misses and disk reads
  • Write non-blocking covering indexes using CONCURRENTLY and INCLUDE
  • Resolve disk spill during large sort operations by tuning work_mem

Example prompts for the agent

  • Analyze this slow orders query using EXPLAIN (ANALYZE, BUFFERS)
  • Design a covering index for status and created_at in PostgreSQL
  • Find the top slow queries from performance_schema in MySQL

How to install database-optimizer

1Skills CLI (Vercel)

npx skills add Jeffallan/claude-skills --skill database-optimizer -a claude-code

2Manually: put the files in place

~/.claude/skills/database-optimizer/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/database-optimizer/

From the same set61

The whole set →
laravel-specialist https://github.com/Jeffallan Configures the agent for Laravel 10+ and PHP 8.2+ development. It guides Eloquent modeling, Horizon queues, API resources, and Pest testing. Claude Code CX Codex Cursor +1 23,300installs golang-pro https://github.com/Jeffallan A Go skill for concurrent code, microservices, performance profiling, and idiomatic interfaces. Use it for goroutines, gRPC, benchmarks, and table-driven tests. Claude Code CX Codex Cursor +1 18,900installs php-pro https://github.com/Jeffallan Enforces PHP 8.3+ standards across Laravel and Symfony projects with strict typing, PHPStan level 9 checks, and automated Pest tests. Claude Code CX Codex Cursor +1 15,500installs flutter-expert https://github.com/Jeffallan Skill for building cross-platform apps with Flutter 3+ and Dart. Covers widgets, state management via Riverpod or Bloc, GoRouter navigation, and performance optimization. Claude Code CX Codex Cursor +1 14,300installs typescript-pro https://github.com/Jeffallan Implements advanced TypeScript type systems, branded types, and tRPC configurations. Use it when building type-first APIs or complex discriminated unions. Claude Code CX Codex Cursor +1 14,200installs kubernetes-specialist https://github.com/Jeffallan This skill helps create and validate Kubernetes manifests, set workload security, and troubleshoot failing pods. Use it for deployment and cluster operations. Claude Code CX Codex Cursor +1 14,100installs devops-engineer https://github.com/Jeffallan This skill creates Dockerfiles, CI/CD configs, Kubernetes manifests, and IaC templates. Use it for deployments, platform work, and incident response. Claude Code CX Codex Cursor +1 11,200installs wordpress-pro https://github.com/Jeffallan This skill builds WordPress themes, plugins, Gutenberg blocks, and WooCommerce features. Use it for REST API work, hooks, security checks, and performance tuning. Claude Code CX Codex Cursor +1 9,700installs

Similar

spring-boot-testing official github Helps choose a testing approach for Spring Boot 4, from a focused slice to a full application test. Use it when deciding which annotations and tools fit a test. GitHub Copilot 2,000installs sentiment-analysis phuryn Analyzes user feedback from surveys and reviews to extract customer segments. Computes sentiment scores from -1 to +1 and maps core jobs via JTBD. Claude Code CX Codex Cursor +1 3,100installs metrics-dashboard phuryn A skill that helps you design a product metrics dashboard with North Star Metric, Input Metrics, Health Metrics, and Business Metrics. Use it when defining KPIs, setting up product analytics, or building a data monitoring plan. Claude Code CX Codex Cursor +1 3,000installs scientific-visualization K-Dense-AI Generates and audits publication-ready scientific figures in Matplotlib, Seaborn, and Plotly, focusing on truthful data encoding and accessibility. Claude Code CX Codex Cursor +1 2,400installs cohort-analysis phuryn Analyzes user engagement data by cohorts, tracks retention curves, and recommends follow-up product research. Claude Code CX Codex Cursor +1 2,900installs ab-test-analysis phuryn Evaluates A/B test data, checks statistical significance, and delivers clear ship, extend, or stop recommendations. Claude Code CX Codex Cursor +1 2,900installs xlsx official anthropics Creates, reads, edits, and converts spreadsheet files. Use it when the requested deliverable is an Excel workbook or another tabular file. Claude Code Claude.ai 187,223installs google-agents-cli-observability official Google This skill guides you through tracing and monitoring AI agents, including ADK agents. Use it when you need to inspect agent execution or monitor a deployed agent. Claude Code CX Codex Cursor +1 509,900installs

Questions about database-optimizer

How do you install database-optimizer in Claude Code?

Run npx skills add Jeffallan/claude-skills --skill database-optimizer -a claude-code. The file will be placed in ~/.claude/skills/database-optimizer/SKILL.md.

What does the database-optimizer skill do?

It provides structured execution plan analysis, slow query detection, and index design strategies across PostgreSQL and MySQL databases.

What database extension is needed for PostgreSQL slow query tracking?

Tracking top slow queries by execution time and call counts requires the pg_stat_statements extension to be enabled in PostgreSQL.

Source text

SKILL.md · MIT
---
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
  company: https://synergetic.solutions
  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

Maintained by [@jeffallan](https://github.com/jeffallan), Principal Consultant at [Synergetic Solutions](https://synergetic.solutions)

[Documentation](https://jeffallan.github.io/claude-skills/skills/infrastructure/database-optimizer/)

© https://github.com/Jeffallan · MIT · Jeffallan/claude-skills

See also

Project sponsors

Companies that keep this analytics open
Gold sponsor

Impressions, clicks and code copies — open statistics. We keep the numbers public for the same reason NeBlask itself is public. Become a sponsor