← Back to Skills Marketplace
goldath

SQL 查询优化助手

by Hjs102468 · GitHub ↗ · v1.0.0 · MIT-0
cross-platform ✓ Security Clean
151
Downloads
0
Stars
2
Active Installs
1
Versions
Install in OpenClaw
/install sql-assistant
Description
Use this skill when you need to write, review, optimize, or debug SQL queries. Covers query construction, performance tuning, index strategy, window function...
README (SKILL.md)

SQL 查询优化助手

核心工作流

Step 1 — 理解需求

收集上下文:

  • 数据库类型(PostgreSQL / MySQL / SQLite / SQL Server)
  • 表结构(DDL 或列描述)
  • 业务目标(查什么、过滤条件、聚合逻辑)
  • 数据量级(小表 \x3C10万 / 中表 \x3C1000万 / 大表 >1000万)
  • 性能问题描述(慢查询?错误结果?)

Step 2 — 查询构建

基础查询框架

SELECT
  col1,
  col2,
  agg_func(col3) AS alias
FROM table_name t
JOIN other_table o ON t.id = o.fk_id
WHERE condition
GROUP BY col1, col2
HAVING agg_condition
ORDER BY alias DESC
LIMIT 100;

CTE 模式(复杂逻辑拆分)

WITH base_data AS (
  SELECT user_id, COUNT(*) AS order_count
  FROM orders
  WHERE created_at >= '2026-01-01'
  GROUP BY user_id
),
ranked AS (
  SELECT *, RANK() OVER (ORDER BY order_count DESC) AS rk
  FROM base_data
)
SELECT * FROM ranked WHERE rk \x3C= 10;

Step 3 — 性能优化策略

索引策略

-- 单列索引
CREATE INDEX idx_orders_user ON orders(user_id);

-- 复合索引(遵循最左前缀原则)
CREATE INDEX idx_orders_user_date ON orders(user_id, created_at);

-- 覆盖索引(避免回表)
CREATE INDEX idx_orders_cover ON orders(user_id, created_at, status, amount);

EXPLAIN 分析

EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)
SELECT * FROM orders WHERE user_id = 42;

关注指标:

  • Seq Scan → 考虑加索引
  • rows 估算偏差大 → 需要 ANALYZE
  • cost 高 → 优化 JOIN 顺序或添加索引
  • Buffers: shared hit/read → 缓存命中率

Step 4 — 常见优化模式

分页优化(大表 OFFSET 慢)

-- ❌ 慢:OFFSET 需扫描丢弃前N行
SELECT * FROM orders ORDER BY id LIMIT 20 OFFSET 100000;

-- ✅ 快:游标分页
SELECT * FROM orders WHERE id > :last_seen_id ORDER BY id LIMIT 20;

IN 子查询优化

-- ❌ 可能慢
SELECT * FROM users WHERE id IN (SELECT user_id FROM premium_members);

-- ✅ 用 EXISTS 或 JOIN
SELECT u.* FROM users u
JOIN premium_members pm ON u.id = pm.user_id;

避免函数破坏索引

-- ❌ 函数包装列,索引失效
WHERE YEAR(created_at) = 2026

-- ✅ 范围条件,索引有效
WHERE created_at >= '2026-01-01' AND created_at \x3C '2027-01-01'

Step 5 — 窗口函数常用模式

-- 分组内排名
ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC)

-- 累计求和
SUM(amount) OVER (PARTITION BY user_id ORDER BY created_at)

-- 环比计算
LAG(revenue, 1) OVER (ORDER BY month) AS prev_month_revenue

-- 移动平均
AVG(score) OVER (ORDER BY date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW)

Step 6 — 查询审查清单

  • SELECT 只取需要的列(避免 SELECT *)
  • WHERE 条件列有索引
  • JOIN 条件有索引
  • 大表分页用游标而非 OFFSET
  • 聚合前先 WHERE 过滤(减少聚合数据量)
  • 复杂逻辑用 CTE 而非嵌套子查询
  • 无 N+1 查询问题

反模式速查

反模式 修复方式
SELECT * 显式列出需要的列
OFFSET 大分页 改用游标/keyset 分页
WHERE 列用函数 改用范围条件
隐式类型转换 确保参数类型匹配
无 LIMIT 的全表扫描 加 LIMIT 或索引过滤
OR 替代 UNION 改用 UNION ALL
Usage Guidance
This skill appears coherent and safe to install: it is purely documentation and advice for SQL tuning and does not try to access your system or request credentials. Before using, avoid pasting production credentials, full connection strings, or highly sensitive PII into prompts; instead provide schema, anonymized sample data, or sanitized EXPLAIN output. If you want the agent to run commands on a server (logs, pt-query-digest, etc.), only allow that on a controlled environment and never share secrets in plain text.
Capability Analysis
Type: OpenClaw Skill Name: sql-assistant Version: 1.0.0 The 'sql-assistant' skill bundle is a collection of documentation and instructions designed to help an AI agent assist users with SQL query writing and optimization. The files (SKILL.md, database-features.md, and query-optimization.md) contain standard SQL best practices, performance tuning guides, and database-specific feature comparisons without any evidence of malicious intent, data exfiltration, or harmful instructions.
Capability Assessment
Purpose & Capability
Name/description (SQL query writing, review, optimization) align with the provided content: guidance on query patterns, EXPLAIN usage, indexing, CTEs, window functions and diagnostics for PostgreSQL/MySQL/SQLite. No unrelated credentials, binaries, or external services are requested.
Instruction Scope
SKILL.md is an instruction-only guide that asks the agent to collect context (DB type, DDL, business goal, data volumes, slow-query descriptions) and to run/advise on EXPLAIN, indexing, and pagination strategies. This stays within scope, but it expects the user to supply schema, queries, or logs which may contain sensitive data — the skill itself does not include steps to connect to remote DBs or exfiltrate data.
Install Mechanism
No install spec, no code files, and no downloads — lowest risk. The included reference files are static documentation only.
Credentials
No environment variables, credentials, or config paths are requested. Examples reference standard DB tools and typical log paths, which is expected for a DBA-oriented guide.
Persistence & Privilege
always is false and the skill is user-invocable only. It does not request persistent system presence or modify other skills/config. Autonomous invocation is allowed by platform default but not combined with other concerning flags.
How to Use
  1. Make sure OpenClaw is installed (local or Docker)
  2. Run the install command in chat: /install sql-assistant
  3. After installation, invoke the skill by name or use /sql-assistant
  4. Provide required inputs per the skill's parameter spec and get structured output
Version History
v1.0.0
Initial release
Metadata
Slug sql-assistant
Version 1.0.0
License MIT-0
All-time Installs 2
Active Installs 2
Total Versions 1
Frequently Asked Questions

What is SQL 查询优化助手?

Use this skill when you need to write, review, optimize, or debug SQL queries. Covers query construction, performance tuning, index strategy, window function... It is an AI Agent Skill for Claude Code / OpenClaw, with 151 downloads so far.

How do I install SQL 查询优化助手?

Run "/install sql-assistant" in the OpenClaw or Claude Code chat to install it in one step — no extra setup required.

Is SQL 查询优化助手 free?

Yes, SQL 查询优化助手 is completely free, licensed under MIT-0. You can download, install and use it at no cost.

Which platforms does SQL 查询优化助手 support?

SQL 查询优化助手 is cross-platform and runs anywhere OpenClaw / Claude Code is available (cross-platform).

Who created SQL 查询优化助手?

It is built and maintained by Hjs102468 (@goldath); the current version is v1.0.0.

💬 Comments