Production-grade SQL optimization for OLTP systems: EXPLAIN/plan analysis, balanced indexing, schema and query design, migrations, backup/recovery, HA, security, and safe performance tuning across PostgreSQL, MySQL, SQL Server, Oracle, SQLite.
Operational guidance for transactional SQL systems. This skill is strongest on PostgreSQL, MySQL, and SQL Server for query tuning, plan analysis, index strategy, connection pressure, lock contention, and safe production changes.
Primary coverage: PostgreSQL, MySQL, SQL Server Lighter coverage: Oracle, SQLite Out of scope: OLAP engines and lakehouse tuning. Use data-lake-platform for ClickHouse, DuckDB, Doris, StarRocks, Iceberg, Delta Lake, or Hudi.
| Script | What it does | Usage |
|--------|-------------|-------|
| scripts/pg_slow_query_triage.sql | Five-section triage report from pg_stat_statements: top by total time, mean time, I/O, variance, and cache-hit ratio | Copy-paste into psql or any SQL client; requires pg_stat_statements extension |
| scripts/explain_collector.py | Runs EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) on a list of queries via psql, outputs JSONL | DATABASE_URL=postgresql://... python explain_collector.py --queries slow.txt |
# Triage: paste directly into psql
psql $DATABASE_URL -f frameworks/shared-skills/skills/data-sql-optimization/scripts/pg_slow_query_triage.sql
# Collect EXPLAIN plans for top queries (production-safe mode):
python scripts/explain_collector.py --queries queries.txt --no-analyze --output plans.jsonl
# Collect with ANALYZE (executes queries — use on a replica):
DATABASE_URL=postgresql://user:pass@replica:5432/db \
python scripts/explain_collector.py --queries queries.txt --output plans.jsonl
| Need | Start Here | Use When |
|------|------------|----------|
| Slow query triage | template-slow-query.md | You need a safe intake before changing anything |
| Plan review | references/explain-analysis.md | You already have EXPLAIN, EXPLAIN ANALYZE, Query Store, or Performance Schema evidence |
| Index design or index removal | references/index-patterns.md | You are deciding whether to add, reshape, make invisible, or drop an index |
| Query rewrite | references/query-tuning-patterns.md | A query shape or estimation problem is the likely bottleneck |
| Connection saturation | references/connection-pooling-patterns.md | App pools, PgBouncer, RDS Proxy, Supavisor, or Cloud SQL pooling are involved |
| Monitoring and alerting | references/monitoring-alerting-patterns.md | You need dashboards, baselines, or alerts for database performance |
| Locking / deadlocks | template-lock-analysis.md | The issue is blocking, deadlocks, or long transactions rather than raw query cost |
| Partitioning | references/partition-strategies.md | Retention, pruning, or table growth is driving the change |
| Backup and recovery design | references/recovery-strategy-design.md | You need a recovery capability mapped to failure scenarios, not just a backup job |
| Security or RLS review | template-security-audit.md | You are reviewing least privilege, SQL injection controls, or tenant isolation |
| Engine | Status | Notes |
|--------|--------|-------|
| PostgreSQL 18 (GA 2025-09-25) | Primary | AIO, skip scan, uuidv7(), statistics retention across pg_upgrade; deepest coverage |
| MySQL 9.7 LTS (GA 2026-04-21) | Primary | Current LTS; HyperGraph optimizer available but not default; 8.4 LTS still supported |
| SQL Server 2025 (GA 2025-11-18) | Primary | IQP 3.0, DOP feedback, OPPO; Query Store on readable secondaries |
| Oracle | Secondary | Use templates and official docs for optimizer-specific edge cases |
| SQLite | Secondary | Focus on indexes, planner behavior, WAL, and PRAGMA optimize |
Invoke this skill for requests about:
pg_stat_statements, MySQL Performance Schema, or SQL Server Query StoreBefore recommending changes, collect:
If any of these are missing, request them or use the intake templates before suggesting a production change.
Run this sequence before recommending any change:
-- PostgreSQL: capture full plan evidence
EXPLAIN (ANALYZE, BUFFERS, 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>;
| Step | What to Check | Red Flag |
|------|---------------|----------|
| 1 | Highest-cost or longest-elapsed operator | Any node consuming >60% of total time |
| 2 | Rows estimated vs rows actual | Ratio >10x in either direction |
| 3 | Loops * rows per loop = total rows processed | High total even if one loop looks cheap |
| 4 | Shared hit vs read buffers (PostgreSQL) | reads >> hits on a hot query |
| 5 | Sort or hash spill | Sort Method: external merge, Hash Batches > 1 |
| 6 | Key/bookmark lookup on hot path | Many per parent row; add INCLUDE columns |
| 7 | Nested loop on large build side | Switch to hash join via statistics fix, not a hint |
| 8 | Waiting time >> execution time | Investigate locks or pool saturation, not the plan |
Bottleneck decision table:
| Plan shows | Likely cause | First lever |
|-----------|-------------|-------------|
| Seq scan, high rows-read/rows-returned | Missing or unusable index | Check predicate sargability; add index |
| Index scan but high loops | N+1 or bad join order | Batch or fix estimation |
| Actual >> estimated rows | Stale/insufficient stats | ANALYZE; CREATE STATISTICS (PG); histogram (MySQL) |
| Plan varies by parameter | Parameter sensitivity | Query Store / OPPO (SQL Server); separate query shapes |
| Sort spill | Projection too wide; no order-aligned index | Narrow projection; add covering index |
| Cheap plan but slow wall time | Waits: locks, I/O, pool | Check pg_stat_activity, wait events, pool stats |
SQL performance request
-> confirm engine, version, workload, and success metric
-> collect evidence: query, schema, indexes, plan, waits, stats
-> classify bottleneck
+-- query shape or estimates -> rewrite/statistics path
+-- missing or excess index -> index trial path
+-- locks or deadlocks -> transaction-shape path
+-- connections -> pool/topology path
+-- table growth -> partition/retention path
-> change one lever at a time
-> verify correctness, latency, reads, locks, and rollback path
If the problem is a slow query
If the likely problem is cardinality or estimator drift
CREATE STATISTICS, pg_upgrade statistics retention, and PG18 planner changesIf 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
Templates live under assets/. Reference guides — load on demand:
work_mem sizing, idle-in-transaction lock cascades, and online schema change tooling (gh-ost vs pt-osc).WHERE. Check workload value, write cost, and plan change.SELECT * and ORM default eager loading in latency-sensitive request paths.Before applying this skill on a non-trivial task, read learnings.consolidated.md in this directory (and learnings.md if present).
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.
npx skills add vasilyu1983/data-sql-optimization下载完整 Skill 目录,包含 SKILL.md 及所有相关文件
Search for places (restaurants, cafes, etc.) via Google Places API proxy on localhost.
Interact with GitHub using the `gh` CLI. Use `gh issue`, `gh pr`, `gh run`, and `gh api` for issues, PRs, CI runs, and advanced queries.
Create or update AgentSkills. Use when designing, structuring, or packaging skills with scripts, references, and assets.
Start voice calls via the OpenClaw voice-call plugin.
Notion API for creating and managing pages, databases, and blocks.
Gemini CLI for one-shot Q&A, summaries, and generation.
Category:developer