sql-optimization

A guide to improving SQL queries, the commands used to read and change data in databases. It covers examining how MySQL and PostgreSQL execute queries and designing indexes that help them find data faster.

In plain words
What is it for?
Use it to inspect MySQL or PostgreSQL execution plans, compare estimated and actual work, choose index columns and order, and create indexes that cover common queries.
Why use it?
It helps identify slow queries, unnecessary full-table scans, sorting, temporary work, and poorly chosen indexes. This makes database performance problems easier to understand and fix.

Skill for Claude CodeCodex

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add skills/chaterm/terminal-skills/sql-optimization
Any agent
npx skills add chaterm/terminal-skills --skill sql-optimization
Clone the repo
git clone --depth 1 https://github.com/chaterm/terminal-skills

Made for: Claude Code, Codex.

Per session 10 Skills are progressive disclosure: only the name and description are preloaded; the body loads when the skill is used.
When invoked 2,070 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5 $0.00010 $0.02070
Opus 5 $0.00005 $0.01035
Sonnet 5 $0.00002 $0.00414
Haiku 4.5 $0.00001 $0.00207

Measured 3d ago against content hash bf610d3d8783, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

sql-optimization scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 3d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

database/sql-optimization/SKILL.md · 284 lines

How it starts

The opening of the file, as written. The whole thing — 284 lines — stays where its author put it; the contents beside it link to each section on GitHub.

SQL 优化与调优

概述

慢查询分析、执行计划、索引优化等通用 SQL 优化技能。

执行计划分析

MySQL EXPLAIN

-- 基础执行计划
EXPLAIN SELECT * FROM users WHERE email = '[email protected]';

-- 详细执行计划
EXPLAIN ANALYZE SELECT * FROM users WHERE email = '[email protected]';

-- JSON 格式
EXPLAIN FORMAT=JSON SELECT * FROM users WHERE email = '[email protected]';

-- 关键字段解读
-- type: 访问类型 (system > const > eq_ref > ref > range > index > ALL)
-- key: 使用的索引
-- rows: 预估扫描行数
-- Extra: 额外信息 (Using index, Using filesort, Using temporary)

PostgreSQL EXPLAIN

-- 基础执行计划
EXPLAIN SELECT * FROM users WHERE email = '[email protected]';

-- 实际执行
EXPLAIN ANALYZE SELECT * FROM users WHERE email = '[email protected]';

-- 详细信息
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT) SELECT * FROM users WHERE email = '[email protected]';

-- 关键指标
-- Seq Scan: 全表扫描
-- Index Scan: 索引扫描
-- Bitmap Index Scan: 位图索引扫描
-- actual time: 实际执行时间
-- rows: 实际返回行数

索引优化

索引设计原则

-- 1. 选择性高的列优先
-- 选择性 = 不同值数量 / 总行数
SELECT COUNT(DISTINCT column) / COUNT(*) AS selectivity FROM table;

-- 2. 复合索引列顺序
-- 遵循最左前缀原则
-- 将选择性高的列放前面
CREATE INDEX idx_user ON users(status, created_at, name);

-- 3. 覆盖索引
-- 索引包含查询所需的所有列
CREATE INDEX idx_covering ON orders(user_id, status, amount);
SELECT user_id, status, amount FROM orders WHERE user_id = 1;

-- 4. 前缀索引(长字符串)
CREATE INDEX idx_email ON users(email(20));

索引使用检查

-- MySQL: 查看索引使用情况
SELECT * FROM sys.schema_index_statistics WHERE table_schema = 'mydb';

-- MySQL: 未使用的索引
SELECT * FROM sys.schema_unused_indexes WHERE object_schema = 'mydb';

-- PostgreSQL: 索引使用统计
SELECT indexrelname, idx_scan, idx_tup_read, idx_tup_fetch
FROM pg_stat_user_indexes
WHERE schemaname = 'public'
ORDER BY idx_scan;

索引失效场景

-- 1. 函数操作
-- 错误
SELECT * FROM users WHERE YEAR(created_at) = 2024;
-- 正确
SELECT * FROM users WHERE created_at >= '2024-01-01' AND created_at < '2025-01-01';

-- 2. 隐式类型转换
-- 错误 (phone 是 varchar)
SELECT * FROM users WHERE phone = 13800138000;
-- 正确
SELECT * FROM users WHERE phone = '13800138000';

-- 3. LIKE 前缀通配符
-- 错误
SELECT * FROM users WHERE name LIKE '%john%';
-- 正确
SELECT * FROM users WHERE name LIKE 'john%';

-- 4. OR 条件
-- 可能不走索引
SELECT * FROM users WHERE status = 1 OR name = 'john';
-- 改写为 UNION
SELECT * FROM users WHERE status = 1
UNION
SELECT * FROM users WHERE name = 'john';

-- 5. NOT IN / NOT EXISTS
-- 尽量避免,改用 LEFT JOIN
SELECT * FROM users WHERE id NOT IN (SELECT user_id FROM orders);
-- 改写
SELECT u.* FROM users u LEFT JOIN orders o ON u.id = o.user_id WHERE o.id IS NULL;

Read the full file on GitHub · 284 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 3d ago First seen · 284 lines · 10 tokens per session scan A bf610d3d8783

Subscribe to this mod's changes

sql-optimization is a skill published in the GitHub repository chaterm/terminal-skills (58 stars, last pushed 6mo ago), licensed Apache-2.0. It adds 10 tokens to every session and 2,070 once invoked, about $0.0001 per session on Opus 5. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-30.