Skip to content
cccskills
FreePublished on GitHub

database-optimizer

Investigate slow PostgreSQL and MySQL queries using execution plans, which show how the database runs a query. Develop index, SQL, and configuration changes, then compare measurements before and after each change to validate the results.

OriginalShow the original 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.

Works withPostgreSQLMySQL
See how to install

Good for

  • Investigating slow SQL queries
  • Reviewing database index design
  • Tuning memory and database configuration
  • Reducing lock contention and deadlocks

Files included (6)

  • SKILL.md6.1 KB
  • references/index-strategies.md7.9 KB
  • references/monitoring-analysis.md14.3 KB
  • references/mysql-tuning.md10.8 KB
  • references/postgresql-tuning.md10.0 KB
  • references/query-optimization.md5.7 KB

SKILL.md (original)

Review the instructions the agent will receive before you install.

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:

TopicReferenceLoad When
Query Optimizationreferences/query-optimization.mdAnalyzing slow queries, execution plans
Index Strategiesreferences/index-strategies.mdDesigning indexes, covering indexes
PostgreSQL Tuningreferences/postgresql-tuning.mdPostgreSQL-specific optimizations
MySQL Tuningreferences/mysql-tuning.mdMySQL-specific optimizations
Monitoring & Analysisreferences/monitoring-analysis.mdPerformance 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

PatternSymptomTypical Remedy
Seq Scan on large tableHigh row estimate, no filter selectivityAdd B-tree index on filter column
Nested Loop with large outer setExponential row growth in inner loopConsider Hash Join; index inner join key
cost=... rows=1 but actual rows=50000Stale statisticsRun ANALYZE <table>;
Buffers: hit=10 read=90000Low buffer cache hit rateIncrease shared_buffers; add covering index
Sort Method: external mergeSort spilling to diskIncrease 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:

  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, Principal Consultant at Synergetic Solutions

Documentation

Reviews

No reviews yet. Tell others what you thought.

Comments

No login needed. Share how it worked for you, ask a question, or note where it did not run.

No comments yet. Be the first to write one.

Comments are published right away. Do not include personal information such as email addresses or phone numbers. Up to 2 URLs.

0 / 1,000 characters

This form is protected by reCAPTCHA, and the Google Privacy Policy and Terms of Service apply.

More skills from this repository

Build Angular 17+ applications with standalone components, routing, and shared application state. Covers reactive data handling with RxJS, performance improvements, and unit and integration tests, with code and explanations of architecture choices.

  • Building Angular screens with standalone components
  • Managing shared application state with NgRx
  • Configuring lazy-loaded routes and access guards
Jeffallan/claude-skills11.9KUpdated Oct 17, 2026

api-designer

FreeSummary

Design REST or GraphQL APIs by defining data relationships, requests, responses, and authentication. Produce OpenAPI specifications, machine-readable API descriptions, with consistent errors, pagination, and versioning plans, then validate contracts using a mock server.

  • Designing a new API from business requirements
  • Creating and validating OpenAPI specifications
  • Standardizing errors and paginated responses
Jeffallan/claude-skills11.9KUpdated Oct 17, 2026

Design or review a system’s overall structure, compare technology choices, and plan for growth and failures. Produce architecture diagrams and Architecture Decision Records, documents that explain key choices, alternatives, and their consequences.

  • Designing the overall structure of a new system
  • Comparing monolith and microservices architectures
  • Recording technology decisions and alternatives
Jeffallan/claude-skills11.9KUpdated Oct 17, 2026

atlassian-mcp

FreeSummary

Connect AI agents to Jira and Confluence through MCP, a protocol for accessing external tools. This skill guides issue searches and updates, page management, sprint workflows, authentication setup, and troubleshooting of Atlassian integrations.

  • Find Jira issues by assignee or status
  • Search and update Confluence pages
  • Turn meeting notes into Jira ticket updates
Jeffallan/claude-skills11.9KUpdated Oct 17, 2026

chaos-engineer

FreeSummary

Design controlled failure experiments for distributed systems to examine how services recover. Produce failure injection scripts, monitoring plans, rollback procedures, and exercise guides, then turn findings into documented improvements.

  • Planning controlled failure experiments
  • Testing recovery after Kubernetes Pod failures
  • Checking service behavior under network delays
Jeffallan/claude-skills11.9KUpdated Oct 17, 2026

cli-developer

FreeSummary

Design and implement command-line tools with subcommands, options, interactive prompts, and progress indicators. Get command structures, configuration handling, clear error messages, and shell completion scripts, with guidance for automated use and testing across operating systems.

  • Build a command-line tool with subcommands and options
  • Add interactive prompts and progress indicators
  • Provide bash, zsh, and fish command completion
Jeffallan/claude-skills11.9KUpdated Oct 17, 2026

See all skills by Jeffallan

Report a problem with this skill