本文へ移動
cccskills
無料GitHub で公開

data-sql-optimization

Diagnoses and tunes SQL for OLTP workloads on PostgreSQL, MySQL, and SQL Server. Use when tuning queries, reading plans, indexing, or fixing lock contention.

インストール方法を見る

含まれるファイル(42)

  • SKILL.md17.0 KB
  • agents/openai.yaml341 B
  • assets/cross-platform/template-backup-restore.md5.9 KB
  • assets/cross-platform/template-diagnostics.md5.5 KB
  • assets/cross-platform/template-explain-analysis.md3.2 KB
  • assets/cross-platform/template-index.md3.9 KB
  • assets/cross-platform/template-lock-analysis.md6.2 KB
  • assets/cross-platform/template-migration.md5.5 KB
  • assets/cross-platform/template-performance-tuning-worksheet.md7.5 KB
  • assets/cross-platform/template-query-tuning.md3.4 KB
  • assets/cross-platform/template-schema-design.md6.3 KB
  • assets/cross-platform/template-security-audit.md5.7 KB
  • assets/cross-platform/template-slow-query.md4.7 KB
  • assets/mssql/template-mssql-explain.md11.0 KB
  • assets/mssql/template-mssql-index.md10.3 KB
  • assets/mysql/template-mysql-explain.md3.5 KB
  • assets/mysql/template-mysql-index.md3.4 KB
  • assets/mysql/template-replication-ha.md13.6 KB
  • assets/oracle/template-oracle-explain.md10.4 KB
  • assets/postgres/template-pg-explain.md3.3 KB
  • assets/postgres/template-pg-index.md3.6 KB
  • assets/postgres/template-pg-rls.md31.7 KB
  • assets/postgres/template-replication-ha.md15.4 KB
  • assets/sqlite/template-sqlite-optimization.md10.2 KB
  • data/sources.json19.7 KB
  • data/versions.json2.3 KB
  • learnings.consolidated.md597 B
  • learnings.md357 B
  • references/connection-pooling-patterns.md10.4 KB
  • references/explain-analysis.md11.9 KB
  • references/index-patterns.md10.1 KB
  • references/monitoring-alerting-patterns.md3.5 KB
  • references/operational-patterns.md15.1 KB
  • references/partition-strategies.md16.2 KB
  • references/query-optimization-research-runtime.md5.4 KB
  • references/query-tuning-patterns.md18.0 KB
  • references/recovery-strategy-design.md15.6 KB
  • references/sql-antipatterns.md14.1 KB
  • references/sql-best-practices.md2.7 KB
  • scripts/explain_collector.py13.8 KB
  • scripts/pg_slow_query_triage.sql13.4 KB
  • scripts/test_explain_collector.py3.4 KB

SKILL.md(原文)

インストールする前に、エージェントに与えられる指示の中身を確認できます。

SQL Optimization

Out of scope: OLAP engines and lakehouse tuning. Use data-lake-platform for ClickHouse, DuckDB, Doris, StarRocks, Iceberg, Delta Lake, or Hudi.

Quick Reference

Scripts

ScriptWhat it doesUsage
scripts/pg_slow_query_triage.sqlSix-section triage report from pg_stat_statements: total time, mean time, I/O, variance, cache-hit ratio, and spills/planning/WALCopy-paste into psql or any SQL client; requires pg_stat_statements extension
scripts/explain_collector.pyCollects estimated JSON plans via psql; --analyze opts into query executionDATABASE_URL=postgresql://... python explain_collector.py --queries slow.txt
scripts/test_explain_collector.pyOffline input, execution-mode and JSON-envelope regressionspython scripts/test_explain_collector.py
# Triage: paste directly into psql
psql "$DATABASE_URL" -f skills/universal/data-sql-optimization/scripts/pg_slow_query_triage.sql

# Collect estimated plans for reviewed queries (default):
python scripts/explain_collector.py --queries queries.txt --no-analyze --output plans.jsonl

# Collect actual plans (executes queries — review side effects first):
DATABASE_URL=postgresql://user:pass@test-db:5432/db \
  python scripts/explain_collector.py --queries queries.txt --analyze --output plans.jsonl
NeedStart HereUse When
Slow query triagetemplate-slow-query.mdYou need a safe intake before changing anything
Plan reviewreferences/explain-analysis.mdYou already have EXPLAIN, EXPLAIN ANALYZE, Query Store, or Performance Schema evidence
Index design or index removalreferences/index-patterns.mdYou are deciding whether to add, reshape, make invisible, or drop an index
Query rewritereferences/query-tuning-patterns.mdA query shape or estimation problem is the likely bottleneck
Connection saturationreferences/connection-pooling-patterns.mdApp pools, PgBouncer, RDS Proxy, Supavisor, or Cloud SQL pooling are involved
Monitoring and alertingreferences/monitoring-alerting-patterns.mdYou need dashboards, baselines, or alerts for database performance
Locking / deadlockstemplate-lock-analysis.mdThe issue is blocking, deadlocks, or long transactions rather than raw query cost
Partitioningreferences/partition-strategies.mdRetention, pruning, or table growth is driving the change
Backup and recovery designreferences/recovery-strategy-design.mdYou need a recovery capability mapped to failure scenarios, not just a backup job
Security or RLS reviewtemplate-security-audit.mdYou are reviewing least privilege, SQL injection controls, or tenant isolation

Coverage Model

EngineStatusNotes
PostgreSQLPrimaryDeepest coverage. Version-gated features used here (skip scan, AIO, uuidv7(), statistics kept across pg_upgrade) arrived in PostgreSQL 18
MySQLPrimaryRecommend an LTS line, not an Innovation release, for production. Check whether the HyperGraph optimizer is on by default in the user's version before relying on its plans
SQL ServerPrimaryUse Query Store for plan regressions; IQP features have different release and compatibility prerequisites. Check the Microsoft feature matrix for the exact feature before recommending it
OracleSecondaryUse templates and official docs for optimizer-specific edge cases
SQLiteSecondaryFocus on indexes, planner behavior, WAL, and PRAGMA optimize

Version lookups: take the user's exact version from SELECT version() (or @@version) first; current minor releases are in data/versions.json (postgresql, mysql), refreshed by script. For which majors or LTS lines are supported and when each reaches end of life, read the vendor's versioning or support-policy page; plan an upgrade before the line in use reaches EOL. Before recommending a feature from a newer major, confirm in the release notes that the major is GA; do not recommend beta-only features for production.

First Response Checklist

Before recommending changes, collect:

  1. Database engine and exact version
  2. Query text or workload shape
  3. Relevant schema, indexes, and estimated row counts
  4. Actual evidence: plan output, wait stats, query stats, or error text
  5. Recent changes: schema, config, deploy, traffic spike, or data skew
  6. Concurrency context: app pool, server pooler, replica topology
  7. Success metric: p95 latency, CPU, reads, lock time, error rate, or connection count

If any of these are missing, request them or use the intake templates before suggesting a production change.

EXPLAIN-Driven Diagnosis Checklist

Start with an estimated plan. Use actual-plan capture only after reviewing the statement, functions and triggers: ANALYZE executes it, and rollback does not undo sequence changes or external effects. The collector accepts one line per statement and rejects internal semicolons, including inside literals/comments.

-- PostgreSQL: estimated plan first; opt into ANALYZE for reviewed execution
EXPLAIN (VERBOSE, FORMAT TEXT) <query>;

-- MySQL: get JSON plan for detailed cost breakdown
EXPLAIN FORMAT=JSON <query>;

-- SQL Server: turn on I/O and CPU evidence
SET STATISTICS IO, TIME ON;
<query>;
StepWhat to CheckRed Flag
1Operator time and loopsParent times include child work; do not sum them or treat cost units as milliseconds
2Rows estimated vs rows actualRatio >10x in either direction
3Loops * rows per loop = total rows processedHigh total even if one loop looks cheap
4Shared hit vs read buffers (PostgreSQL)reads >> hits on a hot query
5Sort or hash spillSort Method: external merge, Hash Batches > 1
6Key/bookmark lookup on hot pathMany per parent row; add INCLUDE columns
7Nested loop outer rows × inner workCheck estimates and repeated inner scans before choosing a join strategy
8Waiting time >> execution timeInvestigate locks or pool saturation, not the plan

Bottleneck decision table:

Plan showsLikely causeFirst lever
Seq scan, high rows-read/rows-returnedMissing/unusable index or valid scan choiceCheck selectivity and sargability; compare an index trial
Index scan but high loopsN+1 or bad join orderBatch or fix estimation
Actual >> estimated rowsStale/insufficient statsANALYZE; CREATE STATISTICS (PG); histogram (MySQL)
Plan varies by parameterParameter sensitivityQuery Store / OPPO (SQL Server); separate query shapes
Sort spillProjection too wide; no order-aligned indexNarrow projection; add covering index
Cheap plan but slow wall timeWaits: locks, I/O, poolCheck pg_stat_activity, wait events, pool stats

Workflow

  1. Confirm the engine, workload, symptom, and evidence available before suggesting a change.
  2. Route search, lakehouse, backend-architecture, or observability-heavy work to the adjacent skill when SQL tuning is not the primary problem.
  3. Gather plans, stats, and workload context before proposing indexes, rewrites, or configuration changes.
  4. Change one lever at a time and verify correctness plus performance impact after each step.
  5. Re-check version-sensitive behavior with the navigation references before final recommendations.

Production Change Gate

Choose proof and rollback by the change being made:

ChangeTrialRollback triggerRollback
Query rewriteReplay representative parameters and concurrency; compare result setsWrong rows or worse p95/reads/locksRevert query or feature flag
New indexBuild with the engine's online/concurrent path where available; confirm chosen plansWrite latency, lock time, or storage exceeds budgetDrop with the safe online path after dependents are checked
Statistics changeCapture plans before/after across skewed valuesRegression for another parameter classRestore target/statistics setting and analyze
Pool/config changeCanary one service or pool; watch waits and saturationQueueing, timeouts, or connection churn risesRestore prior value and recycle only affected pools
Partition/schema changeRehearse on production-shaped data and verify dual reads/writesRow-count mismatch, blocked writers, or replication lagStop cutover and return traffic to old path

Do not declare a tuning win from one warm-cache execution. Record correctness, p50/p95/p99, logical/physical reads, CPU, locks, and write impact over the same workload window; name any metric that could not be measured.

Routing Guide

If the problem is a slow query

If the likely problem is cardinality or estimator drift

If the issue is index design

If the issue is blocking or lock waits

If the issue is connection pressure

If the request is PostgreSQL tenant isolation or privilege review

Navigation and Templates

Load cross-engine worksheets only when documenting the corresponding decision:

DecisionTemplate
Multi-symptom incident diagnosisdiagnostics
Rewrite and result-equivalence reviewquery tuning
New schema or integrity reviewschema design
Record baseline, experiment and verificationtuning worksheet
Record a plan review across enginesEXPLAIN analysis
Record index trial and write impactindex design
Rehearse schema rollout and rollbackmigration
Rehearse recovery and verify recovered databackup/restore
Plan replication topology, lag, and failoverMySQL replication/HA, PostgreSQL replication/HA
Tune an embedded SQLite workloadSQLite optimization

Reference guides — load on demand:

  • references/explain-analysis.md — Load when reading EXPLAIN/EXPLAIN ANALYZE output: row estimates, join order, memory spills, per-engine capture commands.
  • references/index-patterns.md — Load when deciding whether to add, reshape, or retire an index; covers composite, partial, covering, BRIN, invisible, and PG18 skip scan.
  • references/query-tuning-patterns.md — Load when the likely fix is in the SQL itself: sargability, OR rewrites, keyset pagination, N+1 collapse, estimation fixes.
  • references/sql-best-practices.md — Load for workload-grounded tuning defaults and safe-change workflow; useful before making production changes.
  • references/sql-antipatterns.md — Load during schema or query code review to detect and remediate common anti-patterns (SELECT *, N+1, EAV, non-sargable predicates).
  • references/query-optimization-research-runtime.md — Load when a recommendation depends on version-specific engine behavior (PG18 AIO, MySQL HyperGraph, SQL Server 2025 IQP, LITHE rewrite research).
  • references/partition-strategies.md — Load when table growth, retention, or vacuum pressure motivates partitioning; includes migration patterns and pg_partman guidance.
  • references/connection-pooling-patterns.md — Load when the symptom is connection saturation, pooler misconfiguration, or cloud-managed pool selection (PgBouncer, RDS Proxy, Supavisor, Cloud SQL).
  • references/monitoring-alerting-patterns.md — Load when setting up query stats, wait-event monitoring, or alert thresholds for PostgreSQL, MySQL, or SQL Server.
  • references/operational-patterns.md — Load for the production tuning workflow, safe migration checklist, engine-specific operational cautions, work_mem sizing, idle-in-transaction lock cascades, and online schema change tooling (gh-ost vs pt-osc).
  • references/recovery-strategy-design.md — Load when designing or reviewing backup and recovery: failure-scenario taxonomy, detection per failure class, storage tiering, recovery testing as a deliverable.

Primary sources live in data/sources.json.

Known Traps

  • Sequential scans, hash joins, materialization, subqueries and CTEs can be correct choices. Require plan evidence before rewriting.
  • Each added index increases write and maintenance work. Check overlapping indexes and measure write impact alongside read gains.
  • Development data hides production skew and tenant hot spots; compare representative parameters under concurrency.
  • Planner hints and session knobs are diagnostic experiments after query, schema and statistics checks; do not transfer hints across engines.

Related Skills

Learnings Loop

When prior decisions or pitfalls are relevant, consult learnings.consolidated.md if present; use learnings.md only for needed history or as the available fallback. Otherwise skip both.

After applying it, if you encountered a pattern worth remembering, a mistake worth preventing, or a domain fact that surprised you, append one dated bullet to learnings.md via agents-skills-feedback-loop/scripts/append_learning.py. Do not modify SKILL.md itself.

レビュー

まだレビューはありません。使ってみた感想をお寄せください。

同じリポジトリのスキル

概要と使いどころ

Configures Claude Code hooks and Codex hooks.json/notify. Use when adding PreToolUse guards, Stop hooks, managed hooks, format-on-save, preflight, audits, or worktree/budget hooks.

日本語の概要は準備中です。原文の説明を表示しています。

vasilyu1983/AI-Agents-public912026年10月5日 更新

Configures and hardens Claude Code and Codex MCP servers. Use when connecting databases, APIs, SaaS, building servers, or serving a clearance-filtered knowledge base.

日本語の概要は準備中です。原文の説明を表示しています。

vasilyu1983/AI-Agents-public912026年10月5日 更新

Owns instruction files: AGENTS.md, CLAUDE.md, personal and repo rules. Use when writing, pruning, auditing them, sharing rules across Claude and Codex, or fixing ignored rules.

日本語の概要は準備中です。原文の説明を表示しています。

vasilyu1983/AI-Agents-public912026年10月5日 更新

Creates and audits agent skills: SKILL.md, references, scripts, runtime metadata. Use when writing, validating, or security-reviewing a skill, or fixing truncated skill listings.

日本語の概要は準備中です。原文の説明を表示しています。

vasilyu1983/AI-Agents-public912026年10月5日 更新

Adds per-skill learnings loops for dated patterns, mistakes, and domain facts. Use when wiring skill memory, consolidation, or drift audits.

日本語の概要は準備中です。原文の説明を表示しています。

vasilyu1983/AI-Agents-public912026年10月5日 更新

Chooses subagent, team, workflow, or debate and launches it on Claude Code or Codex. Use when delegating, running agent review boards, or installing shared agents.

日本語の概要は準備中です。原文の説明を表示しています。

vasilyu1983/AI-Agents-public912026年10月5日 更新

vasilyu1983 のスキルをすべて見る

このスキルの問題を報告する