Логотип 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, який модель завантажує за потреби, тож токени витрачаються лише тоді, коли запит справді відповідає навичці.

  • Працює з будь-якою LLM

    Навички ШІ — це звичайний 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. Вставте наведений нижче URL папки навички та підтвердьте встановлення.
    https://github.com/vasilyu1983/AI-Agents-public/tree/main/frameworks/shared-skills/skills/data-sql-optimization
  4. Увімкніть навичку в кожному чаті, де хочете її використовувати.
Плагіни → Навички → Додати навичку → За URL GitHub, потім вставте URL папки й натисніть «Продовжити».
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 цю навичку публікує vasilyu1983 за ліцензією MIT. Ви платите лише своєму постачальнику ШІ за використані токени.

Що таке навички ШІ?

Навичка ШІ — це набір інструкцій для повторного використання, який навчає модель ШІ виконувати одне конкретне завдання. Він відповідає відкритому формату 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
Відкрити

Створіть власний робочий простір зі ШІ вже зараз

Підпишіться на нашу розсилку, щоб дізнаватися про нові функції та майбутні розіграші 👇