sql-pro
jeffallan/claude-skills
优化 SQL 查询、设计数据库模式并排查性能问题。当用户询问查询为何运行缓慢、需要帮助编写复杂的连接或聚合语句、提及数据库性能问题,或者希望设计或迁移数据库模式时,可使用此功能。 适用于处理复杂查询、窗口函数、CTE、索引策略、查询计划分析、覆盖索引创建、递归查询、EXPLAIN/ANALYZE 结果解读、查询前后基准测试,或在不同数据库之间迁移查询。
...展开全部关于sql-pro
SQL Pro 是一项专门的 AI 技能,旨在提高数据库查询效率、优化模式设计并排查性能问题。它针对关系型数据库中常见的挑战——例如查询运行缓慢或难以维护——提供解决方案,特别是在处理复杂的连接、聚合或大型数据集时。 通过分析 SQL 查询、执行计划和索引策略,该技能可帮助用户识别瓶颈并实施最佳实践,从而实现更快且更可预测的数据库性能。
该技能提供了一个结构化的工作流:首先进行模式分析,评估数据库结构、索引和查询模式,以精准定位性能瓶颈;随后利用共同表表达式(CTE)、窗口函数和适当的连接策略等高级技术,协助设计查询。 优化功能包括执行计划分析、创建覆盖索引、消除全表扫描,以及通过迭代优化来满足性能目标。 SQL Pro 还强调通过 `EXPLAIN ANALYZE` 输出结果进行验证,以确保查询高效运行且索引得到有效利用。该技能提供关于查询、索引设计依据及性能指标的全面文档,以支持可维护性和知识传承。
SQL Pro 面向使用 PostgreSQL、MySQL、SQL Server 或 Oracle 数据库,且需要在查询调优、模式迁移或性能优化方面具备专业知识的数据库管理员、开发人员和数据工程师。 典型用例包括加速慢查询、设计规范化模式、在不同数据库方言间转换查询、分析执行计划,以及在不牺牲效率的前提下实现复杂分析。 在需要使用递归查询、窗口函数和性能基准测试等高级 SQL 功能的场景中,其指导尤为宝贵,这使其成为致力于维护高性能、可扩展数据库应用程序的团队的关键工具。
常见问题
如何使用 SQL Pro 优化慢查询?
请提供查询语句及相关模式信息。SQL Pro 将分析执行计划,建议索引改进方案,并使用 CTE 或聚合连接等高效模式重写查询。
SQL Pro 支持哪些数据库系统?
SQL Pro 支持 PostgreSQL、MySQL、SQL Server 和 Oracle,并提供了针对这些方言之间差异的指导。
SQL Pro 能否处理包含窗口函数的复杂分析查询?
可以。它提供了在分区内高效使用 ROW_NUMBER、RANK、SUM 以及 LAG/LEAD 等窗口函数的指导,避免不必要的自连接。
在 SQL Pro 中使用 EXPLAIN ANALYZE 时应检查哪些内容?
关键检查包括:检测大型表上的顺序扫描、比较实际行数与预估行数,以及审查缓冲区命中率和读取情况,以识别缺失的索引或过时的统计信息。
使用 SQL Pro 是否有任何限制或先决条件?
用户应具备访问数据库模式的权限,并拥有足够的权限来运行查询和分析执行计划。性能提升取决于正确的索引设置、查询结构以及数据库统计信息。
SQL Pro
Core Workflow
- Schema Analysis - Review database structure, indexes, query patterns, performance bottlenecks
- Design - Create set-based operations using CTEs, window functions, appropriate joins
- Optimize - Analyze execution plans, implement covering indexes, eliminate table scans
- Verify - Run
EXPLAIN ANALYZEand confirm no sequential scans on large tables; if query does not meet sub-100ms target, iterate on index selection or query rewrite before proceeding - Document - Provide query explanations, index rationale, performance metrics
Reference Guide
Load detailed guidance based on context:
| Topic | Reference | Load When |
|---|---|---|
| Query Patterns | references/query-patterns.md | JOINs, CTEs, subqueries, recursive queries |
| Window Functions | references/window-functions.md | ROW_NUMBER, RANK, LAG/LEAD, analytics |
| Optimization | references/optimization.md | EXPLAIN plans, indexes, statistics, tuning |
| Database Design | references/database-design.md | Normalization, keys, constraints, schemas |
| Dialect Differences | references/dialect-differences.md | PostgreSQL vs MySQL vs SQL Server specifics |
Quick-Reference Examples
CTE Pattern
-- Isolate expensive subquery logic for reuse and readabilityWITH ranked_orders AS ( SELECT customer_id, order_id, total_amount, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC) AS rn FROM orders WHERE status = 'completed' -- filter early, before the join)SELECT customer_id, order_id, total_amountFROM ranked_ordersWHERE rn = 1; -- latest completed order per customer
Window Function Pattern
-- Running total and rank within partition — no self-join requiredSELECT department_id, employee_id, salary, SUM(salary) OVER (PARTITION BY department_id ORDER BY hire_date) AS running_payroll, RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS salary_rankFROM employees;
EXPLAIN ANALYZE Interpretation
-- PostgreSQL: always use ANALYZE to see actual row counts vs. estimatesEXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)SELECT *FROM orders oJOIN customers c ON c.id = o.customer_idWHERE o.created_at > NOW() - INTERVAL '30 days';
Key things to check in the output:
- Seq Scan on large table → add or fix an index
- actual rows ≫ estimated rows → run
ANALYZE <table>to refresh statistics - Buffers: shared hit vs read → high
readcount signals missing cache / index
Before / After Optimization Example
-- BEFORE: correlated subquery, one execution per row (slow)SELECT order_id, (SELECT SUM(quantity) FROM order_items oi WHERE oi.order_id = o.id) AS item_countFROM orders o;-- AFTER: single aggregation join (fast)SELECT o.order_id, COALESCE(agg.item_count, 0) AS item_countFROM orders oLEFT JOIN ( SELECT order_id, SUM(quantity) AS item_count FROM order_items GROUP BY order_id) agg ON agg.order_id = o.id;-- Supporting covering index (includes all columns touched by the query)CREATE INDEX idx_order_items_order_qty ON order_items (order_id) INCLUDE (quantity);
Constraints
MUST DO
- Analyze execution plans before recommending optimizations
- Use set-based operations over row-by-row processing
- Apply filtering early in query execution (before joins where possible)
- Use EXISTS over COUNT for existence checks
- Handle NULLs explicitly in comparisons and aggregations
- Create covering indexes for frequent queries
- Test with production-scale data volumes
MUST NOT DO
- Use SELECT * in production queries
- Use cursors when set-based operations work
- Ignore platform-specific optimizations when targeting a specific dialect
- Implement solutions without considering data volume and cardinality
Output Templates
When implementing SQL solutions, provide:
- Optimized query with inline comments
- Required indexes with rationale
- Execution plan analysis
- Performance metrics (before/after)
- Platform-specific notes if applicable
Documentation





首页
