SQL Optimization Patterns
ynulihao/AgentSkillOS
Master SQL query optimization, indexing strategies, and EXPLAIN analysis to dramatically improve database performance and eliminate slow queries.
Generate SQL queries from natural-language requirements using SELECT, JOIN, GROUP BY, window functions, CTEs, and subqueries.
$ npx skills add seb1n/awesome-ai-agent-skills --skill sql-query-generation -a claude-codeProject install by default; add -g for ~/.claude/skills/.
$ gh skill install seb1n/awesome-ai-agent-skills sql-query-generation --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/seb1n/awesome-ai-agent-skills.git skills-src && mkdir -p .claude/skills && cp -r skills-src/data-and-analytics/sql-query-generation .claude/skills/sql-query-generation && 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 "sql-query-generation" agent skill from https://github.com/seb1n/awesome-ai-agent-skills/tree/main/data-and-analytics/sql-query-generation into .claude/skills/sql-query-generation/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "sql-query-generation", 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/seb1n/awesome-ai-agent-skills/tree/main/data-and-analytics/sql-query-generationType 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 seb1n/awesome-ai-agent-skills --skill sql-query-generation -a codexProject install goes to .agents/skills/; add -g for ~/.codex/skills/.
$ gh skill install seb1n/awesome-ai-agent-skills sql-query-generation --agent codexProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/seb1n/awesome-ai-agent-skills.git skills-src && mkdir -p .agents/skills && cp -r skills-src/data-and-analytics/sql-query-generation .agents/skills/sql-query-generation && rm -rf skills-srcUse ~/.agents/skills/ instead of .agents/skills for a personal install.
Codex skills documentation · loads skills from .agents/skills/
Install the "sql-query-generation" agent skill from https://github.com/seb1n/awesome-ai-agent-skills/tree/main/data-and-analytics/sql-query-generation into .agents/skills/sql-query-generation/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "sql-query-generation", 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 seb1n/awesome-ai-agent-skills --skill sql-query-generation -a cursorProject install goes to .agents/skills/; add -g for ~/.cursor/skills/.
$ gh skill install seb1n/awesome-ai-agent-skills sql-query-generation --agent cursorProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/seb1n/awesome-ai-agent-skills.git skills-src && mkdir -p .cursor/skills && cp -r skills-src/data-and-analytics/sql-query-generation .cursor/skills/sql-query-generation && 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 "sql-query-generation" agent skill from https://github.com/seb1n/awesome-ai-agent-skills/tree/main/data-and-analytics/sql-query-generation into .cursor/skills/sql-query-generation/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "sql-query-generation", 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/seb1n/awesome-ai-agent-skills.git --path data-and-analytics/sql-query-generation--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 seb1n/awesome-ai-agent-skills --skill sql-query-generation -a gemini-cliProject install goes to .agents/skills/; add -g for ~/.gemini/skills/.
$ gh skill install seb1n/awesome-ai-agent-skills sql-query-generation --agent gemini-cliProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/seb1n/awesome-ai-agent-skills.git skills-src && mkdir -p .gemini/skills && cp -r skills-src/data-and-analytics/sql-query-generation .gemini/skills/sql-query-generation && 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 "sql-query-generation" agent skill from https://github.com/seb1n/awesome-ai-agent-skills/tree/main/data-and-analytics/sql-query-generation into .gemini/skills/sql-query-generation/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "sql-query-generation", 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 seb1n/awesome-ai-agent-skills sql-query-generationInstalls 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 seb1n/awesome-ai-agent-skills --skill sql-query-generation -a github-copilotProject install goes to .agents/skills/; add -g for ~/.copilot/skills/.
$ git clone --depth 1 https://github.com/seb1n/awesome-ai-agent-skills.git skills-src && mkdir -p .github/skills && cp -r skills-src/data-and-analytics/sql-query-generation .github/skills/sql-query-generation && 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 "sql-query-generation" agent skill from https://github.com/seb1n/awesome-ai-agent-skills/tree/main/data-and-analytics/sql-query-generation into .github/skills/sql-query-generation/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "sql-query-generation", 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 seb1n/awesome-ai-agent-skills --skill sql-query-generation -a opencodeOpenCode documents no install command of its own. Project install goes to .agents/skills/; add -g for ~/.config/opencode/skills/.
$ gh skill install seb1n/awesome-ai-agent-skills sql-query-generation --agent opencodeProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/seb1n/awesome-ai-agent-skills.git skills-src && mkdir -p .opencode/skills && cp -r skills-src/data-and-analytics/sql-query-generation .opencode/skills/sql-query-generation && 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 "sql-query-generation" agent skill from https://github.com/seb1n/awesome-ai-agent-skills/tree/main/data-and-analytics/sql-query-generation into .opencode/skills/sql-query-generation/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "sql-query-generation", 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.
sql-query-generationGenerate SQL queries from natural-language requirements using SELECT, JOIN, GROUP BY, window functions, CTEs, and subqueries.
SQL Query Generation is an agent skill from seb1n/awesome-ai-agent-skills. Generate SQL queries from natural-language requirements using SELECT, JOIN, GROUP BY, window functions, CTEs, and subqueries. Use when the user needs a new query from a business question or schema; use query-optimization when an existing query or execution plan is slow.
Its SKILL.md is about 2.3k 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 SQL and Query optimization. It works with SQL. The repository describes itself as: 103 ready-to-use AI agent skills for Claude Code, OpenAI Codex, Gemini CLI, Cursor, GitHub Copilot, Windsurf, and other Agent Skills-compatible tools. Complete SKILL.md… The licence is MIT.
6 steps, taken from the first numbered list in SKILL.md.
Read from SKILL.md and the folder at commit 75865a5. 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.
SQL Query Generation loads about 2.3k tokens when it runs. Until then it costs about 73 tokens; SKILL.md has 736 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 seb1n/awesome-ai-agent-skills at commit 75865a5, republished under its MIT licence (© seb1n). 736 words, ~2,290 tokens.
.claude/skills/sql-query-generation/SKILL.md (or your agent's skills folder).This skill enables an AI agent to translate natural language questions into correct, efficient SQL queries. The agent maps user intent to the appropriate query constructs — joins, aggregations, window functions, CTEs, and subqueries — while respecting the target database schema. It also analyzes query performance with EXPLAIN plans and recommends optimizations such as indexing, predicate pushdown, and query restructuring.
Parse the natural language request. Extract the analytical intent: what metric is being asked for, which entities are involved, what filters apply, and how results should be ordered or grouped. Distinguish between requests for aggregated summaries versus row-level detail.
Map to the database schema. Identify the relevant tables and columns from the schema. Resolve ambiguous references (e.g., "sales" could mean the orders table or the revenue column). Determine the join path between tables using foreign key relationships, avoiding unnecessary joins that inflate result sets.
Select the appropriate query constructs. Choose between simple aggregation, window functions, CTEs, or subqueries based on complexity. Use CTEs for multi-step calculations to improve readability. Use window functions for running totals, rankings, and comparisons within partitions. Prefer explicit JOINs over implicit comma-separated joins.
Generate the SQL query. Write syntactically correct SQL with consistent formatting: uppercase keywords, lowercase identifiers, aliased tables, and indented clauses. Include comments for complex logic. Always specify column aliases for computed expressions.
Validate and optimize. Run EXPLAIN (or EXPLAIN ANALYZE) on the generated query to inspect the execution plan. Look for full table scans, hash joins on large tables, and sort operations on unindexed columns. Recommend indexes or query rewrites when the estimated cost is high.
Return results with explanation. Present the query alongside a plain-language explanation of what it does, the expected output format, and any assumptions made about the schema or data.
Provide the agent with a natural language question and the database schema (as DDL, a schema diagram, or a list of tables and columns). Optionally specify the target SQL dialect, any performance constraints, and whether you want the EXPLAIN analysis included.
Request: "Show the top 5 customers by total spending in the last 12 months, along with their most frequently ordered product category and how their spending compares to the previous 12-month period."
WITH current_period AS (
SELECT
c.customer_id,
c.customer_name,
SUM(oi.quantity * oi.unit_price) AS total_spent,
COUNT(DISTINCT o.order_id) AS order_count
FROM customers c
JOIN orders o ON c.customer_id = o.customer_id
JOIN order_items oi ON o.order_id = oi.order_id
WHERE o.order_date >= CURRENT_DATE - INTERVAL '12 months'
GROUP BY c.customer_id, c.customer_name
),
previous_period AS (
SELECT
c.customer_id,
SUM(oi.quantity * oi.unit_price) AS prev_total_spent
FROM customers c
JOIN orders o ON c.customer_id = o.customer_id
JOIN order_items oi ON o.order_id = oi.order_id
WHERE o.order_date >= CURRENT_DATE - INTERVAL '24 months'
AND o.order_date < CURRENT_DATE - INTERVAL '12 months'
GROUP BY c.customer_id
),
top_categories AS (
SELECT DISTINCT ON (c.customer_id)
c.customer_id,
pc.category_name AS favorite_category,
COUNT(*) AS category_orders
FROM customers c
JOIN orders o ON c.customer_id = o.customer_id
JOIN order_items oi ON o.order_id = oi.order_id
JOIN products p ON oi.product_id = p.product_id
JOIN product_categories pc ON p.category_id = pc.category_id
WHERE o.order_date >= CURRENT_DATE - INTERVAL '12 months'
GROUP BY c.customer_id, pc.category_name
ORDER BY c.customer_id, COUNT(*) DESC
)
SELECT
cp.customer_name,
cp.total_spent,
cp.order_count,
tc.favorite_category,
pp.prev_total_spent,
ROUND(
(cp.total_spent - COALESCE(pp.prev_total_spent, 0))
/ NULLIF(pp.prev_total_spent, 0) * 100, 1
) AS spending_change_pct
FROM current_period cp
LEFT JOIN previous_period pp ON cp.customer_id = pp.customer_id
LEFT JOIN top_categories tc ON cp.customer_id = tc.customer_id
ORDER BY cp.total_spent DESC
LIMIT 5;
-- Expected output:
-- customer_name | total_spent | order_count | favorite_category | prev_total_spent | spending_change_pct
-- Acme Corp | 284,500.00 | 47 | Electronics | 198,200.00 | 43.5
-- GlobalTech | 231,800.00 | 38 | Software | 245,100.00 | -5.4
-- ...Original slow query (takes 12.4 seconds on 5M rows):
SELECT product_name, SUM(quantity * unit_price) AS revenue
FROM order_items oi, products p, orders o
WHERE oi.product_id = p.product_id
AND oi.order_id = o.order_id
AND o.order_date BETWEEN '2024-01-01' AND '2024-12-31'
GROUP BY product_name
ORDER BY revenue DESC;EXPLAIN ANALYZE output (problem indicators):
Seq Scan on orders o (cost=0.00..98456.00 rows=1245000)
Filter: (order_date >= '2024-01-01' AND order_date <= '2024-12-31')
Rows Removed by Filter: 3755000
Hash Join (cost=98456.00..245678.00 rows=3200000)
Sort (cost=312456.00..312460.00 rows=8500)
Sort Method: external merge Disk: 4096kBIssues identified:
orders — no index on order_datework_memOptimized query:
-- Step 1: Create index (one-time)
CREATE INDEX idx_orders_date ON orders (order_date)
INCLUDE (order_id);
-- Step 2: Rewrite with explicit joins and date index hint
SELECT
p.product_name,
SUM(oi.quantity * oi.unit_price) AS revenue
FROM orders o
JOIN order_items oi ON o.order_id = oi.order_id
JOIN products p ON oi.product_id = p.product_id
WHERE o.order_date BETWEEN '2024-01-01' AND '2024-12-31'
GROUP BY p.product_name
ORDER BY revenue DESC;
-- After optimization: 0.34 seconds (36x faster)
-- EXPLAIN now shows:
-- Index Scan on idx_orders_date (rows=1245000, actual=1243892)
-- Merge Join (cost reduced by 85%)
-- Sort Method: quicksort Memory: 512kBCOUNT(DISTINCT col) over COUNT(*) on joined tables to avoid inflated counts from one-to-many relationships.id, name, status), always qualify with the table alias. Prompt the user for clarification if the natural language request is genuinely ambiguous.SUM, AVG, and COUNT(col) silently ignore NULLs. When NULLs are meaningful (e.g., "no sale"), use COALESCE(col, 0) before aggregating and note the assumption.NULLIF(denominator, 0) to return NULL instead of an error, then handle the NULL in the presentation layer.>= '2024-01-01' AND < '2025-01-01' instead of BETWEEN, which includes the end boundary's midnight.LIMIT in exploratory queries. For production queries, add pagination with OFFSET/FETCH or keyset pagination for better performance on deep pages.© seb1n, MIT. 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 data-and-analytics/sql-query-generation of seb1n/awesome-ai-agent-skills.
Open the folder on GitHubat commit 75865a5
SQL Query Generation 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 |
|---|---|---|---|---|---|---|
| SQL Query Generation this skillseb1n/awesome-ai-agent-skills | 206 | — | ~2.3k | Automated safety check: Pass | MIT | |
| SQL Optimization Patternsynulihao/AgentSkillOS | 617 | 11 repos | ~3.3k | Automated safety check: Pass | None | |
| Query Engine Designrevfactory/claude-code-harness | 120 | — | ~474 | Automated safety check: Pass | None | |
| SQL Optimization Patternssickn33/agentic-awesome-skills | 47k | 1 repos | ~566 | Automated safety check: Pass | MIT | |
| SQL Database Assistantborghei/Claude-Skills | 881 | — | ~1.5k | Automated safety check: Pass | MIT | |
| SQL Optimization InterviewerPrepLabsAI/InterviewMentor | 112 | — | ~2.1k | 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.
revfactory/claude-code-harness
SQL query engine design and implementation guide. An agent skill from revfactory/claude-code-harness.
sickn33/agentic-awesome-skills
Diagnose slow SQL with query plans, preserve query results, and verify indexing or query changes against representative data.
borghei/Claude-Skills
This skill should be used when the user asks to "optimize SQL queries", "explore database schemas", "generate migration SQL", "analyze query performance", or "document database structure".
PrepLabsAI/InterviewMentor
A Data Engineering interviewer focused on database performance.
rileyhilliard/claude-essentials
Staff+ DBA SQL patterns targeting what Claude's defaults miss - multi-column statistics, operator classes, keyset pagination, silent performance anti-patterns.
seb1n/awesome-ai-agent-skills
Plan, execute, document, and retest authorized security assessments of AI agents and multi-agent workflows using safe adversarial cases, synthetic identities, canaries, and evidence-based findings.
seb1n/awesome-ai-agent-skills
Build a preliminary, evidence-based EU AI Act readiness assessment across AI-system inventory, territorial scope, operator roles, prohibited-practice screening, risk classification, transparency…
seb1n/awesome-ai-agent-skills
Design and verify auditable human oversight, approval gates, escalation paths, and safe state transitions for AI agent workflows.
seb1n/awesome-ai-agent-skills
Design, implement, harden, and verify Model Context Protocol (MCP) servers with precise tool contracts, least-privilege authorization, safe transports, structured errors, and interoperability tests.
seb1n/awesome-ai-agent-skills
Audit agent skills, plugins, prompts, manifests, scripts, dependencies, and bundled assets for provenance, prompt-injection, permission, execution, exfiltration, persistence, and update risk.
seb1n/awesome-ai-agent-skills
Inspect, profile, clean, reconcile, analyze, visualize, and verify spreadsheet data while preserving formulas, formatting, types, and source files.
Works with
Categories
Generate SQL queries from natural-language requirements using SELECT, JOIN, GROUP BY, window functions, CTEs, and subqueries. SQL Query Generation is an agent skill from seb1n/awesome-ai-agent-skills. Generate SQL queries from natural-language requirements using SELECT, JOIN, GROUP BY, window functions, CTEs, and subqueries.
SQL Query Generation fits situations like: the user needs a new query from a business question; use query-optimization when an existing query; execution plan is slow.
Run `npx skills add seb1n/awesome-ai-agent-skills --skill sql-query-generation -a claude-code`. Or copy the skill folder (data-and-analytics/sql-query-generation in seb1n/awesome-ai-agent-skills) into .claude/skills/sql-query-generation in your project. Claude Code loads it when a task matches its description.
Run `npx skills add seb1n/awesome-ai-agent-skills --skill sql-query-generation -a codex`. Or copy the skill folder (data-and-analytics/sql-query-generation in seb1n/awesome-ai-agent-skills) into .agents/skills/sql-query-generation 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 seb1n/awesome-ai-agent-skills --skill sql-query-generation -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/sql-query-generation, .gemini/skills/sql-query-generation, .github/skills/sql-query-generation and .opencode/skills/sql-query-generation in your project.
SKILL.md names no scripts, command-line tools or credentials: SQL Query Generation 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.
SQL Query Generation is published under the MIT licence (declared in SKILL.md). It allows redistribution, so the full SKILL.md is shown on this page.
About 2.3k tokens (SKILL.md is roughly 9.2k 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 SQL Query Generation: SQL Optimization Patterns (ynulihao/AgentSkillOS, 617 stars), Query Engine Design (revfactory/claude-code-harness, 120 stars), SQL Optimization Patterns (sickn33/agentic-awesome-skills, 47k stars) and SQL Database Assistant (borghei/Claude-Skills, 881 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.
seb1n (a GitHub user) maintains it in seb1n/awesome-ai-agent-skills, which has 206 GitHub stars. The repository holds 91 skills in this directory. The repository was last updated on August 9, 2026.
Source: seb1n/awesome-ai-agent-skills on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.