sql-query-generation
Installation
Review the source and dependencies with a prompt. A package is available to download.
Install with an AI assistant
Copy the prompt so your assistant can review the pinned revision and dependencies first.
View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "sql-query-generation" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-d62e186c374ee20207f4c0fea4c63069216fc9913aec01d740e346d8cd065709. Verify the upstream source and version against https://skillhub.cn/skills/user_3c6cb52e/sql-query-generation-skillhub before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.
Source and setup
skillhub.cn
Setup guidance pending
See the original source for supported tools, dependencies, and permissions.
Installation test pending
A skill module for SkillHub.
Introduction source: third_party · user_3c6cb52e · 1.0.0 Reference
SkillPi interpretation
- Tasks
- Translation pending; see source documentation.
- Testing
- Not tested
Browse files
Frontmatter
name: sql-query-generation
description: 从自然语言请求生成优化的SQL查询,支持SELECT、JOIN、GROUP BY、窗口函数、CTE和子查询。SQL Query Generation
此技能使AI代理能够将自然语言问题转换为正确且高效的SQL查询。代理将用户意图映射到适当的查询结构——连接、聚合、窗口函数、CTE和子查询,同时尊重目标数据库模式。它还通过EXPLAIN计划分析查询性能,并推荐优化方案,如索引、谓词下推和查询重构。
Workflow
-
解析自然语言请求。提取分析意图:询问的是什么指标,涉及哪些实体,应用了哪些过滤条件,以及结果应如何排序或分组。区分汇总请求与行级明细请求。
-
映射到数据库模式。从模式中识别相关表和列。解决模糊引用(例如,“sales”可能指
orders表或revenue列)。使用外键关系确定表之间的连接路径,避免不必要的连接导致结果集膨胀。 -
选择适当的查询结构。根据复杂度在简单聚合、窗口函数、CTE或子查询之间进行选择。对于多步骤计算使用CTE以提高可读性。使用窗口函数处理运行总计、排名和分区内的比较。优先使用显式JOIN而非隐式的逗号分隔连接。
-
生成SQL查询。编写语法正确的SQL并保持格式一致:关键字大写,标识符小写,表别名,子句缩进。对复杂逻辑添加注释。始终为计算表达式指定列别名。
-
验证和优化。在生成的查询上运行EXPLAIN(或EXPLAIN ANALYZE)以检查执行计划。查找全表扫描、大表上的哈希连接和未索引列上的排序操作。当估计成本较高时推荐添加索引或重写查询。
-
返回结果并附解释。展示查询的同时提供其功能的通俗语言解释、预期输出格式以及关于模式或数据所做的任何假设。
支持的技术
- PostgreSQL — CTE、窗口函数、LATERAL连接、EXPLAIN ANALYZE
- MySQL — 公共表表达式(8.0+)、窗口函数(8.0+)、EXPLAIN FORMAT=JSON
- SQLite — 轻量级查询、窗口函数(3.25+)
- SQL Server — T-SQL扩展、cross apply、查询存储分析
- BigQuery — STRUCT/ARRAY类型、QUALIFY子句、基于插槽的成本估算
Usage
向代理提供自然语言问题和数据库模式(以DDL、模式图或表列列表形式)。可选择指定目标SQL方言、任何性能约束,并决定是否包含EXPLAIN分析。
Examples
示例 1:从自然语言生成复杂分析查询
请求:“显示过去12个月总支出最高的前5名客户,以及他们最常订购的产品类别和他们的支出与上一个12个月期间的比较。”
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
-- ...
示例 2:使用EXPLAIN分析优化慢查询
原始慢查询(在500万行数据上耗时12.4秒):
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 输出(问题指示器):
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
识别出的问题:
- 对
orders表进行顺序扫描 —— 没有对order_date建立索引 - 隐式连接语法隐藏了优化器的连接顺序
- 因为
work_mem不足导致排序溢出到磁盘
优化后的查询:
-- 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
最佳实践
- 始终使用显式JOIN语法而不是逗号分隔的隐式连接 —— 它使意图清晰并防止意外交叉连接。
- 为每个表和每个计算列设置别名以提高可读性,并避免复杂查询中的歧义。
- 使用CTE将复杂查询分解为命名、逻辑步骤,而不是深度嵌套的子查询。
- 尽早过滤:在驱动表上放置WHERE条件以减少数据集大小,在连接放大行数之前进行处理。
- 优先使用
COUNT(DISTINCT col)而非在连接表上使用COUNT(*),以避免一对多关系导致的计数膨胀。 - 在呈现最终查询前始终针对实际模式测试生成的查询 —— 自然语言描述中的列名和类型通常与真实DDL不同。
Edge Cases
- 模糊列名。当多个表具有相同名称的列(如
id、name、status)时,始终使用表别名进行限定。如果自然语言请求确实存在歧义,请提示用户澄清。 - 聚合中的NULL处理。
SUM、AVG和COUNT(col)会静默忽略NULL值。当NULL有意义(例如“无销售”)时,在聚合前使用COALESCE(col, 0)并注明假设。 - 计算指标中的除零问题。将分母包装在
NULLIF(denominator, 0)中以返回NULL而不是错误,然后在展示层处理NULL值。 - 日期/时区不匹配。当按时间戳列过滤日期时,明确边界:使用
>= '2024-01-01' AND < '2025-01-01'而不是BETWEEN,后者包含结束边界的午夜。 - 非常大的结果集。在探索性查询中始终包含
LIMIT。对于生产查询,使用OFFSET/FETCH或键集分页以提高深层页面的性能。
Current listing version
1.0.0
Safety and assessment details
Quality assessment
Out of 100 · Assessment report from SkillPi LAB.
Highlights
- 支持从自然语言生成复杂 SQL 查询,覆盖 JOIN、CTE、窗口函数等高级特性
- 提供 EXPLAIN 性能分析与优化建议,显著提升查询效率
- 兼容 PostgreSQL、MySQL、SQLite、SQL Server、BigQuery 五大主流数据库
Highlights
- description 清晰界定功能边界,涵盖核心能力与优化流程
- 触发词精准覆盖 SELECT、JOIN、GROUP BY、窗口函数、CTE、子查询等关键操作
Highlights
- Workflow 分 6 步清晰拆解执行流程,含出口条件与验证机制
- 提供两个完整端到端示例,包含原始问题、优化前后对比与性能数据
- 涵盖最佳实践与边缘情况处理,文档结构完整且专业
Highlights
- 推荐显式 JOIN、CTE 分解、索引创建等可落地的优化策略
- 覆盖 NULL 处理、除零防护、时区边界等常见异常场景
- 强调在真实模式上测试生成查询,避免列名/类型不匹配问题
The arithmetic mean of the first four original scores, rounded to a whole number.
Static text checks
100 / 100 · skillpi-20261123-no-r3-v1
No current rules matched the text.
This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.
Permissions and checks before use
Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.
These common operations were not identified in the main document. This does not mean no permissions or risks exist.
Security rating and access scope
safe · Static evidence review; not a runtime safety guarantee.
Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.
User discussion
No verified reviews yet.