Database Optimizer

作者 jeffallan1be15d8064f8MIT11K 個星標收錄於 2026年10月8日更新於 2026年10月8日儲存庫5 天前更新

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.

AI 產生的概覽

指導 PostgreSQL 與 MySQL 的資料庫效能調校,涵蓋慢查詢、索引與設定。

功能
此技能為診斷與修復 PostgreSQL 和 MySQL 的資料庫效能問題提供結構化指引。內容涵蓋以 EXPLAIN ANALYZE 擷取基準、找出瓶頸、設計索引與查詢改寫,並用前後指標驗證成效。它也指向隨附的參考文件,涉及查詢最佳化、索引策略、PostgreSQL 與 MySQL 調校以及監控。
適用情境
適合在排查慢查詢、解讀執行計畫或設計索引策略時使用。也適用於設定調校、分割以及減少鎖定競爭或死結。它著重於最佳化工作,而非應用程式功能開發。
執行需求
不含指令碼,僅有指示與參考文件。使用時需要能存取 PostgreSQL 或 MySQL 資料庫,以及 EXPLAIN ANALYZE、pg_stat_statements 或 MySQL performance_schema 等量測工具。

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)

sql
-- Requires pg_stat_statements extensionSELECT 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,       rowsFROM   pg_stat_statementsORDER  BY mean_exec_time DESCLIMIT  20;

Capture an Execution Plan

sql
-- Use BUFFERS to expose cache hit vs. disk read ratioEXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)SELECT o.id, c.nameFROM   orders oJOIN   customers c ON c.id = o.customer_idWHERE  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

sql
-- Covers the filter AND the projected columns, eliminating a heap fetchCREATE INDEX CONCURRENTLY idx_orders_status_created_covering    ON orders (status, created_at)    INCLUDE (customer_id, total_amount);

Validate Improvement

sql
-- Before optimization: save plan & timingEXPLAIN (ANALYZE, BUFFERS) <query>;   -- note "Execution Time: X ms"
-- After optimization: compareEXPLAIN (ANALYZE, BUFFERS) <query>;   -- target meaningful reduction in cost & time
-- Confirm index is actually usedSELECT indexname, idx_scan, idx_tup_read, idx_tup_fetchFROM   pg_stat_user_indexesWHERE  relname = 'orders';

MySQL: Find Slow Queries

sql
-- Inspect slow query log candidatesSELECT * FROM performance_schema.events_statements_summary_by_digestORDER  BY SUM_TIMER_WAIT DESCLIMIT  20;
-- Execution planEXPLAIN FORMAT=JSONSELECT * 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

來源與署名

來源:jeffallan/claude-skills位於skills/database-optimizer提交1be15d8

授權條款: MIT

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架