SQL Optimization Patterns
ynulihao/AgentSkillOS
Master SQL query optimization, indexing strategies, and EXPLAIN analysis to dramatically improve database performance and eliminate slow queries.
Diagnose a slow or expensive query with EXPLAIN and querylog, then propose concrete rewrites and better join strategies.
$ npx skills add chmonitor/chmonitor --skill query-tuning-advisor -a claude-codeProject install by default; add -g for ~/.claude/skills/.
$ gh skill install chmonitor/chmonitor query-tuning-advisor --agent claude-codeProject scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).
$ 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-srcUse ~/.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/
Install the "query-tuning-advisor" agent skill from https://github.com/chmonitor/chmonitor/tree/main/.agents/skills/query-tuning-advisor into .claude/skills/query-tuning-advisor/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "query-tuning-advisor", then confirm the skill loads.Claude Code copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$skill-installer install https://github.com/chmonitor/chmonitor/tree/main/.agents/skills/query-tuning-advisorType this inside Codex. $skill-installer <name> installs a curated skill from openai/skills. The installer writes to $CODEX_HOME/skills (default ~/.codex/skills). Restart Codex if the skill does not show up.
$ npx skills add chmonitor/chmonitor --skill query-tuning-advisor -a codexProject install goes to .agents/skills/; add -g for ~/.codex/skills/.
$ gh skill install chmonitor/chmonitor query-tuning-advisor --agent codexProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/chmonitor/chmonitor.git skills-src && mkdir -p .agents/skills && cp -r skills-src/.agents/skills/query-tuning-advisor .agents/skills/query-tuning-advisor && rm -rf skills-srcUse ~/.agents/skills/ instead of .agents/skills for a personal install.
Codex skills documentation · loads skills from .agents/skills/
Install the "query-tuning-advisor" agent skill from https://github.com/chmonitor/chmonitor/tree/main/.agents/skills/query-tuning-advisor into .agents/skills/query-tuning-advisor/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "query-tuning-advisor", then confirm the skill loads.Codex copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ npx skills add chmonitor/chmonitor --skill query-tuning-advisor -a cursorProject install goes to .agents/skills/; add -g for ~/.cursor/skills/.
$ gh skill install chmonitor/chmonitor query-tuning-advisor --agent cursorProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/chmonitor/chmonitor.git skills-src && mkdir -p .cursor/skills && cp -r skills-src/.agents/skills/query-tuning-advisor .cursor/skills/query-tuning-advisor && rm -rf skills-srcUse ~/.cursor/skills/ instead of .cursor/skills for a personal install.
Cursor skills documentation · loads skills from .cursor/skills/, .agents/skills/, .claude/skills/, .codex/skills/
Install the "query-tuning-advisor" agent skill from https://github.com/chmonitor/chmonitor/tree/main/.agents/skills/query-tuning-advisor into .cursor/skills/query-tuning-advisor/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "query-tuning-advisor", then confirm the skill loads.Cursor copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ gemini skills install https://github.com/chmonitor/chmonitor.git --path .agents/skills/query-tuning-advisor--scope user (default) or --scope workspace; --path is the subfolder of the repo that holds the skill; --consent skips the security confirmation prompt.
$ npx skills add chmonitor/chmonitor --skill query-tuning-advisor -a gemini-cliProject install goes to .agents/skills/; add -g for ~/.gemini/skills/.
$ gh skill install chmonitor/chmonitor query-tuning-advisor --agent gemini-cliProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/chmonitor/chmonitor.git skills-src && mkdir -p .gemini/skills && cp -r skills-src/.agents/skills/query-tuning-advisor .gemini/skills/query-tuning-advisor && rm -rf skills-srcUse ~/.gemini/skills/ instead of .gemini/skills for a personal install, then run /skills reload.
Gemini CLI skills documentation · loads skills from .gemini/skills/, .agents/skills/
Install the "query-tuning-advisor" agent skill from https://github.com/chmonitor/chmonitor/tree/main/.agents/skills/query-tuning-advisor into .gemini/skills/query-tuning-advisor/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "query-tuning-advisor", then confirm the skill loads.Gemini CLI copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ gh skill install chmonitor/chmonitor query-tuning-advisorInstalls for Copilot at project scope by default; add --scope user for a personal install. Preview a skill first with gh skill preview. Needs GitHub CLI 2.90.0 or later (public preview).
$ npx skills add chmonitor/chmonitor --skill query-tuning-advisor -a github-copilotProject install goes to .agents/skills/; add -g for ~/.copilot/skills/.
$ git clone --depth 1 https://github.com/chmonitor/chmonitor.git skills-src && mkdir -p .github/skills && cp -r skills-src/.agents/skills/query-tuning-advisor .github/skills/query-tuning-advisor && rm -rf skills-srcUse ~/.copilot/skills/ instead of .github/skills for a personal install. Commit .github/skills so cloud agent and code review can use it.
GitHub Copilot skills documentation · loads skills from .github/skills/, .claude/skills/, .agents/skills/
Install the "query-tuning-advisor" agent skill from https://github.com/chmonitor/chmonitor/tree/main/.agents/skills/query-tuning-advisor into .github/skills/query-tuning-advisor/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "query-tuning-advisor", then confirm the skill loads.GitHub Copilot copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ npx skills add chmonitor/chmonitor --skill query-tuning-advisor -a opencodeOpenCode documents no install command of its own. Project install goes to .agents/skills/; add -g for ~/.config/opencode/skills/.
$ gh skill install chmonitor/chmonitor query-tuning-advisor --agent opencodeProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/chmonitor/chmonitor.git skills-src && mkdir -p .opencode/skills && cp -r skills-src/.agents/skills/query-tuning-advisor .opencode/skills/query-tuning-advisor && rm -rf skills-srcUse ~/.config/opencode/skills/ instead of .opencode/skills for a personal install.
OpenCode skills documentation · loads skills from .opencode/skills/, .claude/skills/, .agents/skills/
Install the "query-tuning-advisor" agent skill from https://github.com/chmonitor/chmonitor/tree/main/.agents/skills/query-tuning-advisor into .opencode/skills/query-tuning-advisor/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "query-tuning-advisor", then confirm the skill loads.OpenCode copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
query-tuning-advisorDiagnose 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.
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.
7 steps, taken from the step headings in SKILL.md.
Read from SKILL.md and the folder at commit fc39ef0. It shows what the files ask for, not the result of running them.
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.
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.
No URLs in SKILL.md.
From URLs in SKILL.md, links to its own repository left out.
Names no API keys, tokens, secrets or passwords.
From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.
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.
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.
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.
The full file from chmonitor/chmonitor at commit fc39ef0, republished under its GPL-3.0 licence (© chmonitor). 900 words, ~2,403 tokens.
.claude/skills/query-tuning-advisor/SKILL.md (or your agent's skills folder).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.
Never guess. Collect evidence before proposing rewrites.
Step 1 — EXPLAIN INDEXES (call explain_query tool, type INDEXES):
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.ORDER BY.Step 2 — EXPLAIN PLAN (type PLAN, actions=1):
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):
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 5Key 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.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:
PREWHERE manually when the optimizer misses it.PREWHERE that reference non-stored columns or require decompression of wide columns.PREWHERE with FINAL on a ReplacingMergeTree — it can produce wrong results.-- 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.
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.
-- 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)| Situation | Setting |
|---|---|
| Right table fits in memory (default, < ~few GB) | join_algorithm = 'hash' |
| Right table too large for RAM | join_algorithm = 'partial_merge' (spills to disk) |
| Both sides sorted on join key | join_algorithm = 'full_sorting_merge' (no hash table) |
| ClickHouse should decide | join_algorithm = 'auto' (v22.9+) |
| Distributed query, right table is small | GLOBAL JOIN (broadcasts right table to all shards) |
Set per-query: SELECT ... FROM a JOIN b USING (k) SETTINGS join_algorithm = 'partial_merge'
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:
-- 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)ON or USING. A missing condition produces a cross join.read_rows in query_log — if it equals left_rows × right_rows, you have a cartesian product.ClickHouse primary key = ORDER BY columns. Filters on those columns prune granules; filters on other columns scan everything.
-- 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'Add a skip index when you often filter on a non-primary-key column:
-- 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.
SELECT * in aggregation queries — fetch only the columns you aggregate or group on.LIMIT down: use LIMIT in subqueries and CTEs to cap intermediate sets before joining or grouping.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.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.SummingMergeTree or AggregatingMergeTree target and query that instead.User reports: "This query takes 45 seconds and reads 2 billion rows."
-- 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 100Diagnosis:
EXPLAIN INDEXES shows Granules: 9800/9800 → full scan (event_type not in ORDER BY).uniq(session_id) in query_log shows memory_usage = 3.2 GiB.users is 50 M rows — large right table.After:
-- 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 outputRationale:
PREWHERE event_type reads only the narrow column first, skips non-matching granules.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.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.PREWHERE on the most selective cheap column?join_algorithm for table sizes?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.toYear(ts) = 2024) → replace with range filter on raw column.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
Just SKILL.md in .agents/skills/query-tuning-advisor of chmonitor/chmonitor.
Open the folder on GitHubat commit fc39ef0
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.
| Skill | Stars | Used in | Tokens | Auto-check | Licence | Repo updated |
|---|---|---|---|---|---|---|
| Query Tuning Advisor this skillchmonitor/chmonitor | 299 | — | ~2.4k | Automated safety check: Pass | GPL-3.0 | |
| SQL Optimization Patternsynulihao/AgentSkillOS | 617 | 11 repos | ~3.3k | Automated safety check: Pass | None | |
| Cloud Trace Queryinggoogle/skills | 21k | — | ~1.7k | Automated safety check: Pass | Apache-2.0 | |
| Query Engine Designrevfactory/claude-code-harness | 120 | — | ~474 | Automated safety check: Pass | None | |
| Query Plan Snapshot CLIeclipse-rdf4j/rdf4j | 420 | — | ~1.5k | Automated safety check: Pass | BSD-3-Clause | |
| Wp Acf And Content Modelingjorgerosal/wordpress-skills | 101 | — | ~3.2k | Automated safety check: Pass | MIT |
ynulihao/AgentSkillOS
Master SQL query optimization, indexing strategies, and EXPLAIN analysis to dramatically improve database performance and eliminate slow queries.
google/skills
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.
revfactory/claude-code-harness
SQL query engine design and implementation guide. An agent skill from revfactory/claude-code-harness.
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.
jorgerosal/wordpress-skills
WordPress ACF and content modeling review. An agent skill from jorgerosal/wordpress-skills.
affaan-m/ECC
JPA/Hibernate patterns for entity design, relationships, query optimization, transactions, auditing, indexing, pagination, and pooling in Spring Boot.
chmonitor/chmonitor
Non-animation creative direction for HyperFrames videos. An agent skill from chmonitor/chmonitor.
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…
chmonitor/chmonitor
Port an existing Remotion (React) composition to HyperFrames HTML.
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.
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…
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…
Categories
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.
Query Tuning Advisor fits situations like: tasks that involve Query optimization.
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.
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.
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.
SKILL.md names no scripts, command-line tools or credentials: Query Tuning Advisor is instructions for the agent only.
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.
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.
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.
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.
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.
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.