Логотип Data Sql Optimization

Data Sql Optimization

Сообщество
vasilyu1983
data-sql-optimization

Диагностирует и оптимизирует SQL для рабочих нагрузок OLTP в PostgreSQL, MySQL и SQL Server. Используйте при оптимизации запросов, анализе планов выполнения, создании индексов или устранении конкуренции за блокировки.

Обзор

Издательvasilyu1983
РепозиторийAI-Agents-public
Название навыкаdata-sql-optimization
Звёзды
87
Форки
19
Файлы в комплекте
40
ЛицензияMIT
Ссылки
  • Инструкции в формате Markdown

    Модель загружает файл SKILL.md по мере необходимости, поэтому токены расходуются только при подходящем запросе.

  • Работает с любой большой языковой моделью

    Навыки ИИ — это обычный Markdown, а не код для конкретного поставщика, поэтому они работают с GPT, Claude, Gemini, Grok и локальными моделями.

  • Файлы в комплекте: 40

    Скрипты, шаблоны и справочные материалы, которые модель может читать во время работы. Файлы доступны только для чтения и никогда не выполняются.

  • Открытый исходный код

    Издатель навыка на GitHub — vasilyu1983. Перед установкой изучите исходные материалы.

Установка

Установите навык ИИ Data Sql Optimization в TypingMind, чтобы использовать его с любой LLM, или добавьте его в другой агент, который умеет читать SKILL.md.

1

Установка в TypingMind

TypingMind устанавливает навык прямо из его папки на GitHub: читает SKILL.md, собирает файлы ресурсов и сохраняет результат локально.

  1. Откройте приложение и перейдите в раздел «Плагины → Навыки».
  2. Выберите «Установить из GitHub».
  3. Вставьте указанную ниже ссылку на папку навыка и подтвердите установку.
    https://github.com/vasilyu1983/AI-Agents-public/tree/main/frameworks/shared-skills/skills/data-sql-optimization
  4. Включите навык в каждом чате, где хотите его использовать.
Плагины → Навыки → Добавить навык → По ссылке GitHub, затем вставьте ссылку на папку и нажмите «Продолжить».
2

Установка в другом агенте

Любой агент с поддержкой формата Agent Skills может использовать этот навык — скопируйте папку в каталог навыков этого агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/vasilyu1983/AI-Agents-public.git /tmp/AI-Agents-public
mkdir -p .claude/skills
cp -r /tmp/AI-Agents-public/frameworks/shared-skills/skills/data-sql-optimization .claude/skills/data-sql-optimization
После копирования перезапустите Claude Code, чтобы загрузить новый навык.

Использование в TypingMind

Включите навык Data Sql Optimization в любом чате TypingMind, и дальше модель всё сделает сама. Его название и описание хранятся в системном промпте, а при появлении подходящего запроса модель сама загружает полные инструкции. Вам не нужно вызывать навык вручную, и до фактического использования он не расходует токены.

Модель сама загружает навык Data Sql Optimization, как только появляется подходящий для него запрос.

Работает с любой моделью ИИ

Навыки ИИ — это обычные инструкции в Markdown, а не код для конкретного поставщика, поэтому навык Data Sql Optimization не привязан к модели, для которой он был создан. Установите его один раз в TypingMind и используйте с GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama или локальной моделью, которую запускаете самостоятельно, — со своими ключами API.

  • Загружается только при необходимости

    Системный промпт содержит только название и описание. Инструкции загружаются при первом подходящем запросе, поэтому неиспользуемый навык не расходует токены.

  • Меняйте модели прямо в чате

    Навык состоит из инструкций, а не кода, поэтому смена модели не нарушает его работу: новая модель читает тот же файл SKILL.md.

Инструкции навыка

Это содержимое файла SKILL.md, которое загружает модель. Прочитайте его перед установкой: навык — это инструкции, которым будет следовать ваша модель.

SQL Optimization

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.

Quick Reference

Scripts

ScriptWhat it doesUsage
scripts/pg_slow_query_triage.sqlFive-section triage report from pg_stat_statements: top by total time, mean time, I/O, variance, and cache-hit ratioCopy-paste into psql or any SQL client; requires pg_stat_statements extension
scripts/explain_collector.pyRuns EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) on a list of queries via psql, outputs JSONLDATABASE_URL=postgresql://... python explain_collector.py --queries slow.txt
bash
# 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
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
PostgreSQL 18 (GA 2025-09-25)PrimaryAIO, skip scan, uuidv7(), statistics retention across pg_upgrade; deepest coverage
MySQL 9.7 LTS (GA 2026-04-21)PrimaryCurrent LTS; HyperGraph optimizer available but not default; 8.4 LTS still supported
SQL Server 2025 (GA 2025-11-18)PrimaryIQP 3.0, DOP feedback, OPPO; Query Store on readable secondaries
OracleSecondaryUse templates and official docs for optimizer-specific edge cases
SQLiteSecondaryFocus on indexes, planner behavior, WAL, and PRAGMA optimize

Use This Skill When

Invoke this skill for requests about:

  • Slow SQL queries, plan interpretation, or index usage
  • PostgreSQL pg_stat_statements, MySQL Performance Schema, or SQL Server Query Store
  • Missing indexes, over-indexing, invisible-index trials, or composite-index ordering
  • Correlated predicate misestimation, histograms, or extended statistics
  • Lock contention, idle-in-transaction sessions, or deadlock triage
  • Connection storms, pool sizing, PgBouncer modes, RDS Proxy, Supavisor, or Cloud SQL Managed Connection Pooling
  • Partition pruning, retention via detach/drop, or online schema change safety
  • Backup, restore, migration, and replication runbooks
  • Database security reviews, least privilege, or PostgreSQL RLS checks

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

Run this sequence before recommending any change:

sql
-- 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>;
StepWhat to CheckRed Flag
1Highest-cost or longest-elapsed operatorAny node consuming >60% of total time
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 on large build sideSwitch to hash join via statistics fix, not a hint
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 or unusable indexCheck predicate sargability; add index
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.

ASCII Flow

text
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

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

Templates live under assets/. 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 9.7 HyperGraph, SQL Server 2025 IQP 3.0, 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.

Operating Rules

  • Measure before change. A fast guess is still a guess.
  • Correctness beats speed. Verify result equivalence after rewrites.
  • Change one variable at a time when triaging production behavior.
  • Sequential scans, hash joins, and materialization can be correct plans.
  • Subqueries and CTEs are not anti-patterns by default; prove they are the bottleneck before rewriting.
  • Do not add indexes just because a column appears in WHERE. Check workload value, write cost, and plan change.
  • Treat version-sensitive behavior as volatile. For PostgreSQL 18, MySQL 9.7 LTS (or 8.4 LTS), and SQL Server 2025 features, prefer vendor docs over memory.

Known Traps

  • Tuning SQL in isolation without confirming whether the real bottleneck is missing indexes, bad cardinality estimates, lock contention, pool saturation, or ORM query shape.
  • Adding indexes reactively for every slow query and degrading write throughput, autovacuum health, and cache residency.
  • Testing with development-sized datasets and drawing conclusions that collapse under production row counts, skew, or tenant hot spots.
  • Rewriting queries aggressively before examining actual plans with row estimates, memory usage, spill behavior, and join order.
  • Treating pagination, search, or reporting queries as harmless OLTP traffic when they dominate I/O and block core transactional paths.
  • Assuming one engine's plan behavior or hint strategy transfers cleanly between PostgreSQL, MySQL, and SQL Server.

Common Anti-Patterns

  • Solving all latency problems with more indexes instead of fixing query shape, access patterns, or workload isolation.
  • Running large ad hoc analytics directly on the primary OLTP path when summary tables, replicas, or warehouse sync should absorb the load.
  • Using SELECT * and ORM default eager loading in latency-sensitive request paths.
  • Benchmarking single queries without concurrent load, cache-warm versus cold-path comparison, or p95 and p99 visibility.
  • Keeping ineffective or duplicate indexes indefinitely because no index review or usage audit is part of routine operations.
  • Treating planner hints or session-level knobs as the first-line fix instead of a last resort after query, schema, and statistics improvements.

Related Skills

Fact-Checking

  • Verify current external facts, version behavior, and managed-service capabilities against official vendor docs before final answers.
  • Prefer primary sources in data/sources.json.
  • If a current fact cannot be verified, mark it as unverified and avoid prescribing a risky production change.

Learnings Loop

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.

Файлы в комплекте

Модель читает эти файлы по мере необходимости, пока навык загружен. Они доступны только для чтения и никогда не выполняются.

Часто задаваемые вопросы

Что делает навык ИИ Data Sql Optimization?

Диагностирует и оптимизирует SQL для рабочих нагрузок OLTP в PostgreSQL, MySQL и SQL Server. Используйте при оптимизации запросов, анализе планов выполнения, создании индексов или устранении конкуренции за блокировки.

Зачем использовать Data Sql Optimization в TypingMind?

Потому что вы устанавливаете навык один раз и используете его с любой моделью. Data Sql Optimization — это обычный текст в формате Markdown, а не код для конкретного поставщика, поэтому один и тот же навык работает с GPT-5, Claude, Gemini, Grok или локальной моделью. Вы можете менять модель прямо во время чата, и навык продолжит работать. TypingMind использует ваши собственные ключи API, поэтому вы платите поставщикам напрямую, а не оформляете подписку с оплатой за каждое место. Ваши навыки и чаты остаются в вашем собственном хранилище.

Как установить Data Sql Optimization в TypingMind?

В TypingMind откройте «Плагины → Навыки → Установить из GitHub» и вставьте https://github.com/vasilyu1983/AI-Agents-public/tree/main/frameworks/shared-skills/skills/data-sql-optimization. TypingMind прочитает файл SKILL.md, включит сопутствующие файлы в пакет и установит навык, который можно включать отдельно для каждого чата.

Какие модели ИИ могут использовать Data Sql Optimization?

Любая модель, которую вы подключите в TypingMind. Навыки ИИ — это обычные инструкции в формате Markdown, а не код для конкретного поставщика, поэтому GPT, Claude, Gemini, Grok и локальные модели могут загружать этот навык, когда запрос ему соответствует.

Со сколькими моделями ИИ можно использовать Data Sql Optimization?

С любым количеством. В TypingMind вы можете использовать Data Sql Optimization с любой моделью, которая поддерживает навыки, в том числе с GPT, Claude, Gemini, Grok, DeepSeek, Mistral и Llama. Для этого вы используете собственные ключи API.

Бесплатен ли навык ИИ Data Sql Optimization?

Да. Навык опубликован на GitHub по лицензии MIT. Издатель — vasilyu1983. Вы платите только своему поставщику ИИ за использованные токены.

Что такое навыки ИИ?

Навык ИИ — это набор инструкций, которыми модель ИИ может пользоваться каждый раз, когда ей нужно выполнить конкретную задачу. Он соответствует открытому формату Agent Skills: файл SKILL.md с названием и описанием, а также любые скрипты, шаблоны или справочные файлы, которые могут понадобиться модели. Модель читает инструкции, только когда ваш запрос соответствует навыку, поэтому установленный навык ничего не стоит, пока не используется.

Чем навыки ИИ отличаются от плагинов и серверов MCP?

Плагин или сервер MCP даёт модели новые инструменты, которые она может вызывать: при вызове где-то выполняется код и возвращает результат. Навык ИИ, напротив, даёт модели знания и описывает порядок действий: как подойти к задаче, какие шаги выполнить и каким должен быть хороший результат. Навыки — это обычный текст в формате Markdown, поэтому им не нужны сервер, ключ API или среда выполнения, и они работают с любой моделью.

Все
Логотип garrytan

Gstack Openclaw Ceo Review

garrytan
СообществоПопулярный

Используйте этот навык, если вас просят проверить план, подвергнуть предложение критическому разбору, провести проверку в стиле CEO, найти слабые места в подходе, расширить рамки проекта или решить, стоит ли увеличить или сократить план.

19.9K
133.5K
Инструкции
Открыть
Логотип JuliusBrussee

Caveman Stats

JuliusBrussee
СообществоПопулярный

Показывает записанные данные об использовании токенов и чтении из кэша, а также атрибуцию режимов для текущего сеанса Claude Code или помогает найти встроенный отчёт об использовании на хосте. Триггер: /caveman-stats.

6.2K
106.3K
Инструкции
Открыть
Логотип pytorch

Ci Metrics

pytorch
ОрганизацияПопулярный

Запрос данных о CI PyTorch, GitHub Actions, HUD, Grafana и показателях инфраструктуры. Используйте этот навык, когда пользователи спрашивают о длительности CI, сбоях заданий, времени ожидания в очереди, тенденциях рабочих процессов, состоянии раннеров, данных панелей мониторинга или показателях…

31K
103.6K
Файлы: 1
Открыть
Логотип openclaw

Notcrawl

openclaw
ОрганизацияПопулярный

Архив Notion: поиск, актуальность синхронизации, страницы и базы данных, экспорт в Markdown, подсчёт записей в SQL и работа с репозиторием Notcrawl.

82.2K
391K
Файлы: 1
Открыть

Создайте своё рабочее пространство с ИИ прямо сейчас

Подпишитесь на нашу рассылку, чтобы узнавать о новых функциях и предстоящих розыгрышах 👇