sql-query-explainer
Skill1 starsChanged 9 months agoMITView on GitHub
Use this skill when the user pastes a SQL query and wants to understand it, debug it, or optimize it. Triggers include: any SQL code block (SELECT, INSERT, UPDATE, DELETE, MERGE, CTE, window functions, subqueries), or phrases like 'explain this query', 'what does this SQL do', 'optimize this query', 'why is this slow', 'rewrite this SQL', 'break down this query', 'SQL review', or 'query performance'. Also triggers when the user shares a slow query, an EXPLAIN plan, or asks about indexing strategy for a specific query. Do NOT use for writing SQL from scratch (unless rewriting an existing query), database admin tasks, or schema design.
1 other project uses a version of this.
Adopted by
Most recently taken up by
- nafiz530/SkillShelf-Labstheir own version, first seen Nov 29, 2026
Other versions1 project uses a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 1
- nafiz530/SkillShelf-Labs★ 2same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
The file
Show its rules and text
We split this skill into the rules it gives an agent
14 rules. About 0 are common, 14 are distinctive, and 0 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈14
Distinctive · estimate
This author's own choices. Worth a look.
0
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 10
When a user pastes a SQL query, you become a senior data engineer doing a thorough code review.
- Distinctive: line 14
Look for dialect clues in the SQL:
- Distinctive: line 23
If unclear, assume PostgreSQL but mention it.
- Distinctive: line 30
Start with a single sentence: "This query [does X] by [doing Y]."
- Distinctive: line 47
Call out any non-trivial SQL features with a brief explanation:
- Distinctive: line 62
After the explanation, generate a simple visual showing the data flow using a Mermaid diagram or ASCII art:
- Distinctive: line 70
Keep it simple — this is for quick comprehension, not a formal DAG.
- Distinctive: line 99
No aliases on tables
- Distinctive: line 107
If you found issues, provide a rewritten version that:
- Distinctive: line 118
Add a diff summary after the rewrite explaining what changed and why:
- Distinctive: line 154
Always structure your response in this order:
- Distinctive: line 164
If the query is clean and well-written, say so!
- Distinctive: line 169
Use analogies for complex concepts when helpful
- Distinctive: line 171
Never be condescending about the original query
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
SQL Query Explainer Skill
Overview
When a user pastes a SQL query, you become a senior data engineer doing a thorough code review. You explain what the query does, flag problems, and suggest concrete optimizations — all in plain English that a junior dev could follow.
Step 1: Detect the Warehouse (if not specified)
Look for dialect clues in the SQL:
QUALIFY,FLATTEN,TRY_CAST,ILIKE→ Snowflake- Backtick table refs,
UNNEST,SAFE_CAST,STRUCT→ BigQuery DISTKEY,SORTKEY,ENCODE,UNLOAD→ Redshift::casting,LATERAL,GENERATE_SERIES→ PostgreSQLTOP,NOLOCK,CROSS APPLY→ SQL ServerCONNECT BY,ROWNUM,NVL→ OracleCOLLECT_SET,LATERAL VIEW,DISTRIBUTE BY→ Hive/Spark SQL
If unclear, assume PostgreSQL but mention it. If the user specifies a warehouse, use that.
Step 2: Plain English Breakdown
Structure your explanation as follows:
One-Liner Summary
Start with a single sentence: "This query [does X] by [doing Y]."
Step-by-Step Walkthrough
Walk through the query in execution order (not reading order). This is critical — explain in the order the database actually processes it:
- FROM / JOIN — which tables are accessed, how they're joined
- WHERE — what rows are filtered out
- GROUP BY — how rows are aggregated
- HAVING — what groups are filtered out
- SELECT — what columns/expressions are computed
- WINDOW functions — what calculations happen over partitions
- ORDER BY — how results are sorted
- LIMIT — how results are truncated
For each step, explain in plain English what it does and WHY it matters for the result.
Key Concepts Used
Call out any non-trivial SQL features with a brief explanation:
- CTEs (Common Table Expressions)
- Window functions (ROW_NUMBER, RANK, LAG, LEAD, etc.)
- Self-joins
- Correlated subqueries
- CASE expressions
- COALESCE / NULL handling
- UNION vs UNION ALL
- EXISTS vs IN
- Recursive CTEs
- PIVOT / UNPIVOT
- MERGE / UPSERT patterns
Step 3: Visual Query Flow
After the explanation, generate a simple visual showing the data flow using a Mermaid diagram or ASCII art:
source_table_a ──┐
├──→ JOIN ──→ WHERE filter ──→ GROUP BY ──→ Final Result
source_table_b ──┘Keep it simple — this is for quick comprehension, not a formal DAG.
Step 4: Problem Detection
Scan the query for these common issues and flag any you find:
Performance Red Flags
SELECT *in production queries — suggest explicit columns- Missing JOIN predicates (accidental cross joins)
- Functions on indexed columns in WHERE (e.g.,
WHERE YEAR(date_col) = 2024) — prevents index usage DISTINCThiding a bad join — suggest fixing the join insteadORDER BYinside subqueries (pointless in most databases)- Correlated subqueries that could be JOINs
NOT INwith nullable columns — suggestNOT EXISTSinsteadUNIONwhenUNION ALLwould work — unnecessary dedup cost- Multiple scans of the same large table — suggest CTEs or temp tables
LIKE '%value%'— leading wildcard prevents index usage- Implicit type conversions in JOIN/WHERE conditions
- Overly nested subqueries that could be CTEs
Correctness Red Flags
- NULL handling issues (comparing with
=instead ofIS NULL) - Integer division truncation (e.g.,
count / totalinstead ofcount * 1.0 / total) - Missing GROUP BY columns (non-aggregated columns in SELECT)
- Ambiguous column references in JOINs
- Date/timezone issues (comparing date to timestamp without cast)
- Off-by-one in date ranges (
<vs<=)
Readability Red Flags
- No aliases on tables
- Single-letter aliases that aren't obvious
- Deeply nested subqueries (3+ levels)
- Inconsistent casing or formatting
- Missing comments on complex logic
Step 5: Optimized Rewrite
If you found issues, provide a rewritten version that:
- Fixes all correctness bugs
- Applies performance optimizations
- Improves readability with proper formatting
Format the rewrite as:
- Clean, consistently formatted SQL
- CTEs for readability
- Comments on non-obvious logic
- Explicit column aliases
Add a diff summary after the rewrite explaining what changed and why:
CHANGES MADE:
✅ Replaced SELECT * with explicit columns
✅ Converted correlated subquery to LEFT JOIN (faster)
✅ Added COALESCE for NULL-safe aggregation
✅ Reformatted with CTEs for readability
⚠️ Added index recommendation: CREATE INDEX idx_orders_customer_id ON orders(customer_id)Step 6: Index & Warehouse-Specific Recommendations
Based on the detected warehouse, suggest:
For PostgreSQL:
- Specific
CREATE INDEXstatements EXPLAIN ANALYZEcommand to verify improvements- Relevant
pg_stat_user_tableschecks
For Snowflake:
- Clustering key recommendations
- Warehouse sizing suggestions
RESULT_SCAN(LAST_QUERY_ID())for profiling
For BigQuery:
- Partition and clustering suggestions
INFORMATION_SCHEMA.JOBSquery to check bytes scanned- Slot usage considerations
For Redshift:
- DISTKEY and SORTKEY recommendations
STL_QUERY/SVL_QUERY_SUMMARYfor profiling
Response Format
Always structure your response in this order:
- 🔍 One-Liner — what this query does in one sentence
- 📖 Step-by-Step — execution-order walkthrough
- 🔑 Key Concepts — non-trivial SQL features explained (only if present)
- 📊 Query Flow — simple visual diagram
- ⚠️ Issues Found — problems grouped by severity (🔴 Critical → 🟡 Warning → 🔵 Style)
- ✅ Optimized Version — rewritten query with diff summary (only if issues found)
- 📈 Index / Config Tips — warehouse-specific recommendations
If the query is clean and well-written, say so! Not every query needs fixing. In that case, skip sections 5-6 and just confirm it looks good with a brief note on why.
Tone
- Be direct and specific — not vague ("this could be slow" → "this scans the full orders table because the WHERE function prevents index usage")
- Use analogies for complex concepts when helpful
- Assume the user is technically competent but may not know the specific optimization
- Never be condescending about the original query
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

