MCPInstall

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.

Installs
231
Last 24h
—
Trending rank
—
Security
Not audited

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/vasilyu1983/ai-agents-public --skill data-sql-optimization
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads data-sql-optimization automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

SKILL.md

The instructions your agent reads when the skill is triggered.

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

  • Start with template-slow-query.md
  • Then use:
    • PostgreSQL: template-pg-explain.md
    • MySQL: template-mysql-explain.md
    • SQL Server: template-mssql-explain.md
    • Oracle: template-oracle-explain.md

If the likely problem is cardinality or estimator drift

  • PostgreSQL: check references/operational-patterns.md for CREATE STATISTICS, pg_upgrade statistics retention, and PG18 planner changes
  • MySQL: use histograms and optimizer statistics in references/operational-patterns.md
  • SQL Server: inspect Query Store, parameter sensitivity, and OPPO in template-mssql-explain.md

If the issue is index design

  • Start with references/index-patterns.md
  • Use vendor templates:
    • PostgreSQL: template-pg-index.md
    • MySQL: template-mysql-index.md
    • SQL Server: template-mssql-index.md

If the issue is blocking or lock waits

  • Use template-lock-analysis.md
  • Favor transaction-shape fixes before configuration changes

If the issue is connection pressure

  • Use references/connection-pooling-patterns.md
  • Distinguish connection helpers from actual poolers. Cloud SQL Auth Proxy and language connectors are not poolers by themselves.

If the request is PostgreSQL tenant isolation or privilege review

  • Use template-pg-rls.md
  • Pair with template-security-audit.md

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

  • software-backend - Application query generation, ORM behavior, and API/database interaction
  • software-security-appsec - SQL injection prevention, auth, secrets, and hardening
  • ops-devops-platform - Infrastructure, failover automation, and operational runbooks
  • qa-observability - Telemetry, alerting, and SLO design
  • qa-debugging - Production incident debugging workflow
  • data-lake-platform - OLAP engines, Parquet, and warehouse/lakehouse tuning

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.

FAQ

What does the data-sql-optimization skill do?

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

How do I install data-sql-optimization?

Run npx skills add https://github.com/vasilyu1983/ai-agents-public --skill data-sql-optimization in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/data-sql-optimization/ (personal) or .claude/skills/data-sql-optimization/ (project).

Which AI agents can use data-sql-optimization?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is data-sql-optimization safe to install?

No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.

Who maintains data-sql-optimization?

It is published by vasilyu1983 in vasilyu1983/ai-agents-public. It has 231 recorded installs.

More from vasilyu1983/ai-agents-public

View all →

software-architecture-design

vasilyu1983/ai-agents-public

Designs runtime topology in a chosen solution. Use when choosing monolith vs services, cells, consistency, ADRs. Not for cross-system design (software-solution-architecture).

product-management

vasilyu1983/ai-agents-public

Guides founder-PM discovery, roadmaps, prioritization, and PMF measurement. Use when planning product strategy, metrics, or roadmaps.

AI & Agents914 installs

document-xlsx

vasilyu1983/ai-agents-public

Builds Excel charts, pivots, validation, exports, Office Scripts/Graph automation, and workbook audits. Use when automating workbooks; for plain edits prefer official xlsx skill.

Data & Databases875 installs

software-ui-ux-design

vasilyu1983/ai-agents-public

Designs and audits UI/UX systems with usability and accessibility requirements. Use when shaping flows, design systems, interaction patterns, or WCAG-aware product behavior.

Frontend & Design731 installs

document-pdf

vasilyu1983/ai-agents-public

Handles PDF/UA accessibility, real redaction, metadata scrubbing, signing, and extraction. Use when redacting or signing PDFs; for plain create/merge prefer the official pdf skill.

Docs & Writing689 installs

qa-testing-playwright

vasilyu1983/ai-agents-public

Builds and debugs Playwright E2E suites. Use when authoring browser tests, fixing flakes, or hardening Playwright CI and locator strategy.

Testing & QA665 installs

Popular data & databases skills

View category →

Postgres best practices maintained by Supabase, for Postgres running anywhere. Load this skill BEFORE writing or changing anything that lives in a Postgres database: creating or altering tables and columns (including choosing column types), schema design, migrations and declarative schema files, RLS policies and the tests that verify them, indexes, triggers, database functions, queues and scheduled jobs (pgcron, pgmq), vector/semantic search (pgvector), and restoring dumps (pgrestore) or importing data. Also load it when diagnosing slow queries, high CPU, timeouts, EXPLAIN plans, connection exhaustion, locking, bloat, or rows visible to the wrong user or tenant. This is not just a performance guide — schema, migration, security, and SQL authoring tasks need these rules too, even for a one-column change or a single query.

OfficialData & Databases462.2K installs

prisma-client-api

prisma/skills

Prisma Client API reference covering model queries, filters, operators, and client methods. Use when writing database queries, using CRUD operations, filtering data, or configuring Prisma Client. Triggers on "prisma query", "findMany", "create", "update", "delete", "$transaction".

OfficialData & Databases393.5K installs

Deprecated compatibility name for prisma-orm-setup. Use only when a user or existing integration explicitly invokes prisma-database-setup; otherwise select prisma-orm-setup.

OfficialData & Databases392.3K installs

prisma-cli

prisma/skills

Prisma ORM 7 CLI reference for existing Prisma 7 applications or explicitly selected Prisma 7 workflows. Covers prisma init, generate, migrate, db, dev, studio, and mcp. For setup, connection repair, or Prisma 8, use prisma-orm-setup; not the Prisma Platform CLI.

OfficialData & Databases390.8K installs

prisma-postgres

prisma/skills

Deprecated compatibility name for prisma-postgres-setup. Use only when a user or existing integration explicitly invokes prisma-postgres; otherwise select prisma-postgres-setup.

OfficialData & Databases384.4K installs

Required reference for Prisma ORM 7 SQL driver adapter work. Use when implementing or modifying adapters, adding database drivers, or touching SqlDriverAdapter, Transaction, savepoint, result mapping, or DriverAdapterError behavior. Covers current transaction lifecycle, optional savepoint hooks, original database-error preservation, and verification.

OfficialData & Databases378.9K installs