Agent skill

SQL Query Generation

by seb1n in seb1n/awesome-ai-agent-skills

Generate SQL queries from natural-language requirements using SELECT, JOIN, GROUP BY, window functions, CTEs, and subqueries.

MITAuto-check passedDatabases

Install SQL Query Generation

skills CLI
$ npx skills add seb1n/awesome-ai-agent-skills --skill sql-query-generation -a claude-code

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

GitHub CLI
$ gh skill install seb1n/awesome-ai-agent-skills sql-query-generation --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/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-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
sql-query-generation
GitHub stars
206
Token cost
~2.3k tokens
SKILL.md length
736 words
Files
1
Skills in repo
91
Repo updated
First seen
Licence
MIT

At a glance

Generate SQL queries from natural-language requirements using SELECT, JOIN, GROUP BY, window functions, CTEs, and subqueries.

  • Works in 6 steps: Parse the natural language request.… → Map to the database schema. Identify the… → Select the appropriate query constructs.… → …
  • The user needs a new query from a business question
  • SKILL.md covers Workflow, Supported Technologies, Usage and Examples, plus 2 more sections
  • Instructions only: no scripts, shell commands, URLs or credentials in SKILL.md

What it does

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.

When your agent uses it

  • The user needs a new query from a business question
  • Use query-optimization when an existing query
  • Execution plan is slow

Example prompts

  • “/sql-query-generation”

Workflow steps

6 steps, taken from the first numbered list in SKILL.md.

  1. Parse the natural language request. Extract the analytical intent: what metric is being asked for, which entities are involved, what…
  2. Map to the database schema. Identify the relevant tables and columns from the schema. Resolve ambiguous references (e.g., "sales" could…
  3. Select the appropriate query constructs. Choose between simple aggregation, window functions, CTEs, or subqueries based on complexity. Use…
  4. Generate the SQL query. Write syntactically correct SQL with consistent formatting: uppercase keywords, lowercase identifiers, aliased…
  5. Validate and optimize. Run EXPLAIN (or EXPLAIN ANALYZE) on the generated query to inspect the execution plan. Look for full table scans…
  6. Return results with explanation. Present the query alongside a plain-language explanation of what it does, the expected output format, and…

What it can do on your machine

Read from SKILL.md and the folder at commit 75865a5. 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

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.

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

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 seb1n/awesome-ai-agent-skills at commit 75865a5, republished under its MIT licence (© seb1n). 736 words, ~2,290 tokens.

Download SKILL.mdSave it as .claude/skills/sql-query-generation/SKILL.md (or your agent's skills folder).
name
sql-query-generation
description
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.
license
MIT
metadata.author
awesome-ai-agent-skills
metadata.version
1.0.0

SQL Query Generation

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.

Workflow

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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.

  6. 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.

Supported Technologies

  • PostgreSQL — CTEs, window functions, LATERAL joins, EXPLAIN ANALYZE
  • MySQL — common table expressions (8.0+), window functions (8.0+), EXPLAIN FORMAT=JSON
  • SQLite — lightweight queries, window functions (3.25+)
  • SQL Server — T-SQL extensions, cross apply, query store analysis
  • BigQuery — STRUCT/ARRAY types, QUALIFY clause, slot-based cost estimation

Usage

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.

Examples

Example 1: Complex analytics query from natural language

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."

sql
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
-- ...
Show full SKILL.md (311 more words)Show less
Example 2: Optimizing a slow query with EXPLAIN analysis

Original slow query (takes 12.4 seconds on 5M rows):

sql
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: 4096kB

Issues identified:

  1. Sequential scan on orders — no index on order_date
  2. Implicit join syntax hides join order from optimizer
  3. Sort spilling to disk due to insufficient work_mem

Optimized query:

sql
-- 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: 512kB

Best Practices

  • Always use explicit JOIN syntax instead of comma-separated implicit joins — it makes intent clear and prevents accidental cross joins.
  • Alias every table and every computed column for readability and to avoid ambiguity in complex queries.
  • Use CTEs to break complex queries into named, logical steps rather than deeply nesting subqueries.
  • Filter early: place WHERE conditions on the driving table to reduce the dataset before joins amplify row counts.
  • Prefer COUNT(DISTINCT col) over COUNT(*) on joined tables to avoid inflated counts from one-to-many relationships.
  • Always test generated queries against the actual schema before presenting them as final — column names and types in natural language descriptions often differ from the real DDL.

Edge Cases

  • Ambiguous column names. When multiple tables have a column with the same name (e.g., id, name, status), always qualify with the table alias. Prompt the user for clarification if the natural language request is genuinely ambiguous.
  • NULL handling in aggregations. 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.
  • Division by zero in calculated metrics. Wrap denominators with NULLIF(denominator, 0) to return NULL instead of an error, then handle the NULL in the presentation layer.
  • Date/time zone mismatches. When filtering by date on a timestamp column, be explicit about boundaries: use >= '2024-01-01' AND < '2025-01-01' instead of BETWEEN, which includes the end boundary's midnight.
  • Very large result sets. Always include 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

Files

Just SKILL.md in data-and-analytics/sql-query-generation of seb1n/awesome-ai-agent-skills.

Open the folder on GitHubat commit 75865a5

Compare with similar skills

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.

SQL Query Generation compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
SQL Query Generation this skillseb1n/awesome-ai-agent-skills206—~2.3kAutomated safety check: PassMIT
SQL Optimization Patternsynulihao/AgentSkillOS61711 repos~3.3kAutomated safety check: PassNone
Query Engine Designrevfactory/claude-code-harness120—~474Automated safety check: PassNone
SQL Optimization Patternssickn33/agentic-awesome-skills47k1 repos~566Automated safety check: PassMIT
SQL Database Assistantborghei/Claude-Skills881—~1.5kAutomated safety check: PassMIT
SQL Optimization InterviewerPrepLabsAI/InterviewMentor112—~2.1kAutomated 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
  • 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
  • SQL Optimization Patterns

    sickn33/agentic-awesome-skills

    Diagnose slow SQL with query plans, preserve query results, and verify indexing or query changes against representative data.

    47k GitHub starsUsed in 1 repo~566 tokens
    DatabasesAuto-check passed
  • SQL Database Assistant

    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".

    881 GitHub stars~1.5k tokensUpdated yesterday
    DatabasesAuto-check passed
  • SQL Optimization Interviewer

    PrepLabsAI/InterviewMentor

    A Data Engineering interviewer focused on database performance.

    112 GitHub stars~2.1k tokensUpdated 2 days ago
    DatabasesAuto-check passed
  • Writing SQL

    rileyhilliard/claude-essentials

    Staff+ DBA SQL patterns targeting what Claude's defaults miss - multi-column statistics, operator classes, keyset pagination, silent performance anti-patterns.

    130 GitHub stars~627 tokensUpdated 1 mo ago
    DatabasesAuto-check passed

More from seb1n/awesome-ai-agent-skills

All 91 skills in this repo
  • Agent Red Teaming

    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.

    206 GitHub stars~2.8k tokensUpdated 2 mo ago
    Auto-check passed
  • Eu AI Act Readiness

    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…

    206 GitHub stars~3.3k tokensUpdated 2 mo ago
    Auto-check passed
  • Human In The Loop

    seb1n/awesome-ai-agent-skills

    Design and verify auditable human oversight, approval gates, escalation paths, and safe state transitions for AI agent workflows.

    206 GitHub stars~2.5k tokensUpdated 2 mo ago
    Auto-check passed
  • MCP Server Building

    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.

    206 GitHub stars~2.5k tokensUpdated 2 mo ago
    Auto-check passed
  • Skill Supply Chain Audit

    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.

    206 GitHub stars~2.4k tokensUpdated 2 mo ago
    Auto-check passed
  • Spreadsheet Analysis

    seb1n/awesome-ai-agent-skills

    Inspect, profile, clean, reconcile, analyze, visualize, and verify spreadsheet data while preserving formulas, formatting, types, and source files.

    206 GitHub stars~2.5k tokensUpdated 2 mo ago
    Auto-check passed

Works with

Categories

Questions about SQL Query Generation

What does SQL Query Generation do?

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.

When should I use SQL Query Generation?

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.

How do I install SQL Query Generation in Claude Code?

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.

How do I install SQL Query Generation in Codex?

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.

Can I use SQL Query Generation 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 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.

What does SQL Query Generation need to run?

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

Does SQL Query Generation 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 SQL Query Generation 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 SQL Query Generation use?

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.

How many tokens does SQL Query Generation use?

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.

What are the alternatives to SQL Query Generation?

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.

Who maintains SQL Query Generation?

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.