Agent skill

Query Tuning Advisor

by chmonitor in chmonitor/chmonitor

Diagnose a slow or expensive query with EXPLAIN and querylog, then propose concrete rewrites and better join strategies.

GPL-3.0Auto-check passedDatabases

Install Query Tuning Advisor

skills CLI
$ npx skills add chmonitor/chmonitor --skill query-tuning-advisor -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install chmonitor/chmonitor query-tuning-advisor --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/chmonitor/chmonitor.git skills-src && mkdir -p .claude/skills && cp -r skills-src/.agents/skills/query-tuning-advisor .claude/skills/query-tuning-advisor && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
query-tuning-advisor
GitHub stars
299
Token cost
~2.4k tokens
SKILL.md length
900 words
Files
1
Skills in repo
53
Repo updated
First seen
Licence
GPL-3.0

At a glance

Diagnose a slow or expensive query with EXPLAIN and querylog, then propose concrete rewrites and better join strategies.

  • Works in 7 steps: Diagnose First → PREWHERE and Predicate Placement → Better JOINs → …
  • Tasks that involve Query optimization
  • SKILL.md covers 1. Diagnose First, 2. PREWHERE and Predicate…, 3. Better JOINs and 4. Avoiding Full Scans, plus 4 more sections
  • Instructions only: no scripts, shell commands, URLs or credentials in SKILL.md

What it does

Query Tuning Advisor is an agent skill from chmonitor/chmonitor. Diagnose a slow or expensive query with EXPLAIN and querylog, then propose concrete rewrites and better join strategies.

Its SKILL.md is about 2.4k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.

It sits in Databases, covering Query optimization. The repository describes itself as: Open-source operational advisor for ClickHouse — real-time monitoring plus AI-driven index/partition/materialized-view recommendations. The licence is GPL-3.0.

When your agent uses it

  • Tasks that involve Query optimization

Example prompts

  • “/query-tuning-advisor”

Workflow steps

7 steps, taken from the step headings in SKILL.md.

  1. Diagnose First
  2. PREWHERE and Predicate Placement
  3. Better JOINs
  4. Avoiding Full Scans
  5. Aggregation Tuning
  6. Before → After Worked Example
  7. Tuning Checklist

What it can do on your machine

Read from SKILL.md and the folder at commit fc39ef0. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md (its code samples are sql).

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Query Tuning Advisor loads about 2.4k tokens when it runs. Until then it costs about 36 tokens; SKILL.md has 900 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~36
When it runs · the whole SKILL.md, loaded when a task matches
~2.4k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from chmonitor/chmonitor at commit fc39ef0, republished under its GPL-3.0 licence (© chmonitor). 900 words, ~2,403 tokens.

Download SKILL.mdSave it as .claude/skills/query-tuning-advisor/SKILL.md (or your agent's skills folder).
name
query-tuning-advisor
description
Diagnose a slow or expensive query with EXPLAIN and query_log, then propose concrete rewrites and better join strategies.

Query Tuning Advisor

Use this skill when a user shares a specific slow, expensive, or high-memory query and wants it made faster. The goal is a concrete before → after rewrite, not general advice. Load query-optimization for reference tables on EXPLAIN output and skip index types.

1. Diagnose First

Never guess. Collect evidence before proposing rewrites.

Step 1 — EXPLAIN INDEXES (call explain_query tool, type INDEXES):

sql
EXPLAIN INDEXES = 1 <the query>

Read the output for:

  • Granules: N/M — N granules selected out of M total. N ≈ M means a full scan; skip indexes are not firing.
  • Keys: <expr> — confirms which primary key ranges were used.
  • Missing keys = predicates don't align with the table's ORDER BY.

Step 2 — EXPLAIN PLAN (type PLAN, actions=1):

sql
EXPLAIN actions = 1 <the query>

Look for: Filter, ReadFromMergeTree with no pushdown, large Aggregating steps, or a JOIN where the build side is large.

Step 3 — Find it in query_log (call query tool):

sql
SELECT
    query_duration_ms,
    read_rows,
    result_rows,
    read_rows / nullIf(result_rows, 0) AS scan_ratio,
    memory_usage,
    ProfileEvents['SelectedMarks']        AS marks_read,
    ProfileEvents['SelectedRangesOfMarks'] AS ranges_read,
    query
FROM system.query_log
WHERE type = 'QueryFinish'
  AND is_initial_query = 1
  AND normalized_query_hash = cityHash64('<the query with literals replaced by ?>')
ORDER BY event_time DESC
LIMIT 5

Key signals:

  • scan_ratio > 100 → reading far more rows than returned; likely full scan or missing PREWHERE.
  • marks_read close to total table marks → primary key not used.
  • memory_usage > 1 GiB → GROUP BY or JOIN materializing too much.

2. PREWHERE and Predicate Placement

ClickHouse evaluates PREWHERE before reading all columns — it reads only the filter column(s) first, skips non-matching granules, then fetches the rest. The optimizer promotes simple WHERE conditions automatically, but it doesn't always get it right.

Rules:

  • Move the most selective, cheapest-to-read condition into PREWHERE manually when the optimizer misses it.
  • Avoid expressions in PREWHERE that reference non-stored columns or require decompression of wide columns.
  • Never use PREWHERE with FINAL on a ReplacingMergeTree — it can produce wrong results.
sql
-- Before
SELECT url, status, body
FROM access_log
WHERE toDate(event_time) = today()
  AND status = 500

-- After: push the narrow int filter to PREWHERE
SELECT url, status, body
FROM access_log
PREWHERE status = 500
WHERE toDate(event_time) = today()

Also: move date/time range filters to align with the primary key order so they prune granules before PREWHERE even runs.


3. Better JOINs

Join order

ClickHouse's hash join builds a hash table from the right table and probes with the left table. Put the smaller table on the right.

sql
-- Before: large table on right (built into hash table)
SELECT * FROM small_dim JOIN large_fact USING (id)

-- After: large table on left (probed), small on right (built)
SELECT * FROM large_fact JOIN small_dim USING (id)
Choose the right join_algorithm
SituationSetting
Right table fits in memory (default, < ~few GB)join_algorithm = 'hash'
Right table too large for RAMjoin_algorithm = 'partial_merge' (spills to disk)
Both sides sorted on join keyjoin_algorithm = 'full_sorting_merge' (no hash table)
ClickHouse should decidejoin_algorithm = 'auto' (v22.9+)
Distributed query, right table is smallGLOBAL JOIN (broadcasts right table to all shards)

Set per-query: SELECT ... FROM a JOIN b USING (k) SETTINGS join_algorithm = 'partial_merge'

IN / semi-join instead of JOIN

When you only need to filter rows (not project columns from the right side), IN is cheaper than JOIN — it avoids materializing the joined columns:

sql
-- Before: full JOIN just to filter
SELECT l.* FROM orders l JOIN vip_customers r ON l.customer_id = r.id

-- After: semi-join via IN
SELECT * FROM orders WHERE customer_id IN (SELECT id FROM vip_customers)
Avoid cartesian blowups
  • Always specify ON or USING. A missing condition produces a cross join.
  • Check read_rows in query_log — if it equals left_rows × right_rows, you have a cartesian product.
  • For many-to-many relationships, pre-aggregate one side before joining.

4. Avoiding Full Scans

Align filters with ORDER BY / primary key

ClickHouse primary key = ORDER BY columns. Filters on those columns prune granules; filters on other columns scan everything.

sql
-- Table: ORDER BY (tenant_id, event_date, event_type)
-- Bad: event_type filter alone cannot prune granules
WHERE event_type = 'purchase'

-- Good: leading columns first, then event_type
WHERE tenant_id = 42 AND event_date >= '2024-01-01' AND event_type = 'purchase'
Skip indexes

Add a skip index when you often filter on a non-primary-key column:

sql
-- For low-cardinality status columns
ALTER TABLE events ADD INDEX idx_status (status) TYPE set(100) GRANULARITY 4;

-- For high-cardinality string equality (e.g. trace_id)
ALTER TABLE events ADD INDEX idx_trace (trace_id) TYPE bloom_filter GRANULARITY 1;

-- For range queries on a secondary numeric column
ALTER TABLE events ADD INDEX idx_latency (latency_ms) TYPE minmax GRANULARITY 4;

After adding, materialize: ALTER TABLE events MATERIALIZE INDEX idx_status;

Verify it fires: EXPLAIN INDEXES = 1 <query> — look for the index name in the output and a reduced granule count.


Show full SKILL.md (382 more words)Show less

5. Aggregation Tuning

  • Avoid SELECT * in aggregation queries — fetch only the columns you aggregate or group on.
  • Push LIMIT down: use LIMIT in subqueries and CTEs to cap intermediate sets before joining or grouping.
  • Use approximate functions when exactness isn't required:
    • uniqHLL12(x) instead of uniq(x) or COUNT(DISTINCT x) — ~1% error, 10× less memory.
    • quantileTDigest(0.95)(latency) instead of quantile(0.95)(latency) — mergeable, streaming-friendly.
    • topK(10)(x) instead of GROUP BY x ORDER BY count() DESC LIMIT 10 for heavy-hitter approximation.
  • GROUP BY memory: if memory_usage is high on aggregation, try max_bytes_before_external_group_by to spill to disk, or switch to two-level aggregation with group_by_two_level_threshold.
  • Pre-aggregate with materialized views: if the same aggregation runs frequently, maintain a SummingMergeTree or AggregatingMergeTree target and query that instead.

6. Before → After Worked Example

User reports: "This query takes 45 seconds and reads 2 billion rows."

sql
-- BEFORE
SELECT
    user_id,
    COUNT(*) AS cnt,
    uniq(session_id) AS sessions
FROM events
JOIN users ON events.user_id = users.id
WHERE event_type = 'page_view'
  AND toYear(event_time) = 2024
GROUP BY user_id
ORDER BY cnt DESC
LIMIT 100

Diagnosis:

  1. EXPLAIN INDEXES shows Granules: 9800/9800 → full scan (event_type not in ORDER BY).
  2. uniq(session_id) in query_log shows memory_usage = 3.2 GiB.
  3. users is 50 M rows — large right table.

After:

sql
-- AFTER
SELECT
    user_id,
    COUNT(*) AS cnt,
    uniqHLL12(session_id) AS sessions   -- ~1% error, 10x less memory
FROM events
PREWHERE event_type = 'page_view'       -- PREWHERE prunes granules early
WHERE event_time >= '2024-01-01'        -- aligns with ORDER BY (event_time in PK)
  AND event_time <  '2025-01-01'
GROUP BY user_id
ORDER BY cnt DESC
LIMIT 100
-- users JOIN removed: not needed for this output

Rationale:

  • PREWHERE event_type reads only the narrow column first, skips non-matching granules.
  • Date range on event_time (primary key leading column) prunes ~90% of granules.
  • uniqHLL12 cuts aggregation memory from 3.2 GiB to ~300 MiB.
  • JOIN users removed — user_id is already in events, users columns not projected.

7. Tuning Checklist

Run through this when asked "make this query faster":

  • EXPLAIN INDEXES — are granules being pruned? If N ≈ M, filters don't hit primary key.
  • EXPLAIN PLAN — is there a large build-side JOIN? A fat Aggregating step?
  • query_log — check scan_ratio (read_rows / result_rows) and memory_usage.
  • Filters on primary key leading columns? If not, reorder WHERE or add skip index.
  • PREWHERE on the most selective cheap column?
  • JOIN: smaller table on the right? Right join_algorithm for table sizes?
  • Can JOIN be replaced by IN (semi-join) if right-side columns aren't projected?
  • SELECT * → replace with explicit column list.
  • uniq() / COUNT(DISTINCT) → uniqHLL12() if approximate is fine.
  • quantile() → quantileTDigest() for percentile aggregations.
  • Frequent aggregation → candidate for a materialized view pre-aggregation.
  • Date arithmetic in WHERE (toYear(ts) = 2024) → replace with range filter on raw column.

Cross-references

  • query-optimization — EXPLAIN output reference, ProfileEvents counters, optimizer settings.
  • schema-design-advisor — fixing slow queries at the schema level (ORDER BY, partition key, skip indexes at table creation).
  • data-analysis — exploratory SQL patterns for understanding data shape before tuning.
  • system-tables-reference — exact column names for system.query_log, system.processes.

© chmonitor, GPL-3.0. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

Just SKILL.md in .agents/skills/query-tuning-advisor of chmonitor/chmonitor.

Open the folder on GitHubat commit fc39ef0

Compare with similar skills

Query Tuning Advisor next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Query Tuning Advisor compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Query Tuning Advisor this skillchmonitor/chmonitor299—~2.4kAutomated safety check: PassGPL-3.0
SQL Optimization Patternsynulihao/AgentSkillOS61711 repos~3.3kAutomated safety check: PassNone
Cloud Trace Queryinggoogle/skills21k—~1.7kAutomated safety check: PassApache-2.0
Query Engine Designrevfactory/claude-code-harness120—~474Automated safety check: PassNone
Query Plan Snapshot CLIeclipse-rdf4j/rdf4j420—~1.5kAutomated safety check: PassBSD-3-Clause
Wp Acf And Content Modelingjorgerosal/wordpress-skills101—~3.2kAutomated safety check: PassMIT

Similar skills

  • SQL Optimization Patterns

    ynulihao/AgentSkillOS

    Master SQL query optimization, indexing strategies, and EXPLAIN analysis to dramatically improve database performance and eliminate slow queries.

    617 GitHub starsUsed in 11 repos~3.3k tokens
    DatabasesAuto-check passed
  • Official

    Query Cloud Trace spans, filter by latency thresholds or error status, correlate distributed traces with Cloud Logging, and diagnose latency bottlenecks across Google Cloud services.

    21k GitHub stars~1.7k tokensUpdated today
    DatabasesAuto-check passed
  • Query Engine Design

    revfactory/claude-code-harness

    SQL query engine design and implementation guide. An agent skill from revfactory/claude-code-harness.

    120 GitHub stars~474 tokensUpdated 7 mo ago
    DatabasesAuto-check passed
  • Query Plan Snapshot CLI

    eclipse-rdf4j/rdf4j

    Use QueryPlanSnapshotCli to capture and compare RDF4J query plans, then assess likely performance improvements/regressions from execution verification and semantic plan diffs.

    420 GitHub stars~1.5k tokensUpdated today
    DatabasesAuto-check passed
  • Wp Acf And Content Modeling

    jorgerosal/wordpress-skills

    WordPress ACF and content modeling review. An agent skill from jorgerosal/wordpress-skills.

    101 GitHub stars~3.2k tokensUpdated 4 mo ago
    DatabasesAuto-check passed
  • Jpa Patterns

    affaan-m/ECC

    JPA/Hibernate patterns for entity design, relationships, query optimization, transactions, auditing, indexing, pagination, and pooling in Spring Boot.

    275k GitHub starsUsed in 5 repos~1.2k tokens
    DatabasesAuto-check passed

More from chmonitor/chmonitor

All 53 skills in this repo
  • Hyperframes Creative

    chmonitor/chmonitor

    Non-animation creative direction for HyperFrames videos. An agent skill from chmonitor/chmonitor.

    299 GitHub starsUsed in 5 repos~1.3k tokens
    Auto-check passed
  • Hyperframes Media

    chmonitor/chmonitor

    Audio and media assets for HyperFrames compositions, produced by one shared audio engine (scripts/audio.mjs) — multi-provider TTS (HeyGen / ElevenLabs / Kokoro local), background music + sound…

    299 GitHub starsUsed in 1 repo~2.8k tokens
    Auto-check: notes
  • Remotion To Hyperframes

    chmonitor/chmonitor

    Port an existing Remotion (React) composition to HyperFrames HTML.

    299 GitHub starsUsed in 1 repo~2.5k tokens
    Auto-check passed
  • Music To Video

    chmonitor/chmonitor

    A skill your agent uses when the user has a music track (an audio file, or a video to pull audio from) and wants a beat-synced HyperFrames video, calm to hard-hitting.

    299 GitHub starsUsed in 1 repo~4k tokens
    Auto-check: notes
  • Hyperframes Animation

    chmonitor/chmonitor

    All animation knowledge for HyperFrames — atomic motion rules, multi-phase scene blueprints, scene transitions, broader motion-design techniques, AND the seven runtime adapters (GSAP default, plus…

    299 GitHub starsUsed in 2 repos~1.8k tokens
    Auto-check passed
  • Faceless Explainer

    chmonitor/chmonitor

    turn arbitrary text — an article, notes, a topic, a brief — into a faceless explainer video, up to ~3 min (sweet spot 30-90s), where every visual is invented (typography, abstract graphics…

    299 GitHub stars~4.5k tokensUpdated 2 days ago
    Auto-check: notes

Categories

Questions about Query Tuning Advisor

What does Query Tuning Advisor do?

Diagnose a slow or expensive query with EXPLAIN and querylog, then propose concrete rewrites and better join strategies. Query Tuning Advisor is an agent skill from chmonitor/chmonitor. Diagnose a slow or expensive query with EXPLAIN and querylog, then propose concrete rewrites and better join strategies.

When should I use Query Tuning Advisor?

Query Tuning Advisor fits situations like: tasks that involve Query optimization.

How do I install Query Tuning Advisor in Claude Code?

Run `npx skills add chmonitor/chmonitor --skill query-tuning-advisor -a claude-code`. Or copy the skill folder (.agents/skills/query-tuning-advisor in chmonitor/chmonitor) into .claude/skills/query-tuning-advisor in your project. Claude Code loads it when a task matches its description.

How do I install Query Tuning Advisor in Codex?

Run `npx skills add chmonitor/chmonitor --skill query-tuning-advisor -a codex`. Or copy the skill folder (.agents/skills/query-tuning-advisor in chmonitor/chmonitor) into .agents/skills/query-tuning-advisor in your project. Codex loads it when a task matches its description.

Can I use Query Tuning Advisor in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add chmonitor/chmonitor --skill query-tuning-advisor -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/query-tuning-advisor, .gemini/skills/query-tuning-advisor, .github/skills/query-tuning-advisor and .opencode/skills/query-tuning-advisor in your project.

What does Query Tuning Advisor need to run?

SKILL.md names no scripts, command-line tools or credentials: Query Tuning Advisor is instructions for the agent only.

Does Query Tuning Advisor access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Query Tuning Advisor safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Query Tuning Advisor use?

Query Tuning Advisor is published under the GPL-3.0 licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Query Tuning Advisor use?

About 2.4k tokens (SKILL.md is roughly 9.6k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Query Tuning Advisor?

Skills that share tags, products or a category with Query Tuning Advisor: SQL Optimization Patterns (ynulihao/AgentSkillOS, 617 stars), Cloud Trace Querying (google/skills, 21k stars), Query Engine Design (revfactory/claude-code-harness, 120 stars) and Query Plan Snapshot CLI (eclipse-rdf4j/rdf4j, 420 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Query Tuning Advisor?

chmonitor (a GitHub organization) maintains it in chmonitor/chmonitor, which has 299 GitHub stars. The repository holds 53 skills in this directory. The repository was last updated on October 5, 2026.

Source: chmonitor/chmonitor on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.