tidb-query-tuning
БесплатноБез исполняемых скриптовНе проверенDiagnose and optimize slow TiDB queries using optimizer hints, session variables, join strategy selection, subquery optimization, and index tuning. Use when a…
от pingcap★ 27 звёзд на GitHubОб этом скилле
TiDB Query Tuning
Use this skill to diagnose and resolve TiDB query performance issues. It follows a rigorous workflow from symptom identification to verified solution.
Workflow
Capture the current plan & clues:
- Run
EXPLAIN ANALYZE <query>to get actual execution stats. - Compare
estRowsvsactRows— large divergence means stale or missing statistics. - Note the most expensive operators (wall time, memory, rows processed).
- Use PLAN REPLAYER: Run
PLAN REPLAYER DUMP EXPLAIN [ANALYZE] <query>;to export comprehensive on-site information (version, config, stats, plan) to a ZIP file. - Use Debug API: Use TiDB HTTP API (port 10080) to pull runtime info:
/debug/pprof,/stats/dump/{db}/{table}, or/schema/{db}/{table}. - Check Bindings: Run
SHOW GLOBAL BINDINGS;to see if existing plan baselines are affecting the query.
- Run
Check statistics health:
SHOW STATS_HEALTHY WHERE Db_name = '<db>' AND Table_name = '<table>';- If health < 80 or
actRowsdiverges significantly fromestRows, runANALYZE TABLE <table>;(or withALL COLUMNSif@@tidb_analyze_column_optionsis notALL) and re-check the plan. - For specific indexes:
ANALYZE TABLE <table> INDEX <index_name>;
Identify the bottleneck pattern:
- Bad join order or strategy → see
references/join-strategies.md IndexJoin/IndexHashJoinpicked the wrong probe index → seereferences/join-strategies.md,references/index-selection.md, andreferences/slow-plan-optimization/cases/use-correct-probe-index-for-index-join.md- Subquery not handled well → see
references/subquery-optimization.md - Wrong or missing index → see
references/index-selection.md - Optimizer choosing a suboptimal plan despite good stats → see
references/optimizer-hints.mdandreferences/session-variables.md - Stats are stale or auto analyze cannot keep up → see
references/stats-health-and-auto-analyze.md - Plans change after restart or sync stats loading times out → see
references/stats-loading-and-startup.md - Need to tune analyze version, column coverage, or memory-heavy stats collection → see
references/stats-version-and-analyze-configuration.md - Need a matching field incident, workaround, or fixed-version precedent → search
references/optimizer-oncall-experiences-redacted/ - Need recent customer issue precedents with linked PRs and merge timestamps → search
references/tidb-customer-planner-issues/
- Bad join order or strategy → see
Reproduce & Investigate locally:
- Local Reproduction: Use
tiup playgroundandPLAN REPLAYER LOADto reproduce the issue locally. Seereferences/plan-replayer-testing.md. - Test Versions: Verify the fix in newer stable versions or
nightly. - Deep Code Analysis: If the cause is still unclear, clone
pingcap/tidband analyze the source code. Read AGENTS.md and .agents/skills in the TiDB repo first.
- Local Reproduction: Use
Apply the fix:
- Prefer the least invasive change: refresh stats → add index → SQL Binding → hint → session variable.
- SQL Binding: Fix plans without code changes:
CREATE GLOBAL BINDING FOR <stmt> USING <hinted_stmt>;. - Validate index-based join probe paths: When the plan uses
IndexJoinorIndexHashJoin, inspect the probe-sideaccess object, pushed conditions, and whether the path is covering. Do not assume the chosen probe index is correct just because the join type is index-based. If another existing index better matches join keys, selective filters, or covering needs, compare it withUSE_INDEX/IGNORE_INDEXand stabilize the winner with a hint or SQL binding. - Binding cleanup safety: TiDB currently has no batch-delete API for global bindings. Do not run
DELETEonmysql.bind_infodirectly. UseDROP GLOBAL BINDING ...for each target binding instead. - If direct delete was already executed:
ADMIN RELOAD BINDINGSmay still leave stale entries in the in-memory binding cache. In this case, restart the TiDB server to fully clear and rebuild binding cache state. - See
references/optimizer-oncall-experiences-redacted/direct-delete-bind-info-leaves-stale-binding-cache.mdfor a full reproduction and recovery checklist. - Hints & Variables: Use hints when the fix is query-specific; use session variables when it applies to a workload pattern.
- Bug Report: If it's a confirmed bug, follow the workflow in
references/bug-report.md. Anonymize all sensitive data before reporting.
Verify the improvement:
- Re-run
EXPLAIN ANALYZEwith the fix applied. - Confirm
actRowsand execution time improved. - If the fix is a hint, document it in a SQL comment so future readers understand why.
- Re-run
High CPU Workflow
When the customer reports high TiDB CPU usage, use the following workflow before jumping to optimizer conclusions:
- Treat
clinic-apias the default entry point. If `
Установить tidb-query-tuning в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл tidb-query-tuning?
Diagnose and optimize slow TiDB queries using optimizer hints, session variables, join strategy selection, subquery optimization, and index tuning. Use when a query is slow, produces a bad plan, or needs performance guidance on TiDB.
Как установить скилл tidb-query-tuning?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл tidb-query-tuning запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic