Optimizing Sql 标志

Optimizing Sql

社区
ancoleman
optimizing-sql

Optimize SQL query performance through EXPLAIN analysis, indexing strategies, and query rewriting for PostgreSQL, MySQL, and SQL Server. Use when debugging slow queries, analyzing execution plans, or improving database performance.

概览

发布者ancoleman
代码仓库ai-design-components
技能名称optimizing-sql
星标数
525
复刻数
77
附带文件
13
许可协议MIT
链接
  • Markdown 格式的指令

    模型按需加载 SKILL.md 文件,因此只有在请求确实与该技能匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 13 个附带文件

    模型执行任务时可读取的脚本、模板和参考资料。这些文件为只读文件,绝不会被执行。

  • 开源

    由 ancoleman 发布于 GitHub。请在安装前查看技能的源文件。

安装

在 TypingMind 中安装 Optimizing Sql AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/ancoleman/ai-design-components/tree/main/skills/optimizing-sql
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

任何支持 Agent Skills 格式的智能体都可以使用此技能,只需将文件夹复制到该智能体的技能目录中。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/ancoleman/ai-design-components.git /tmp/ai-design-components
mkdir -p .claude/skills
cp -r /tmp/ai-design-components/skills/optimizing-sql .claude/skills/optimizing-sql
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 Optimizing Sql,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 Optimizing Sql。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 Optimizing Sql 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会加载完整指令,因此技能未使用时,这些指令不会消耗 Token。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

SQL Optimization

Provide tactical guidance for optimizing SQL query performance across PostgreSQL, MySQL, and SQL Server through execution plan analysis, strategic indexing, and query rewriting.

When to Use This Skill

Trigger this skill when encountering:

  • Slow query performance or database timeouts
  • Analyzing EXPLAIN plans or execution plans
  • Determining index requirements
  • Rewriting inefficient queries
  • Identifying query anti-patterns (N+1, SELECT *, correlated subqueries)
  • Database-specific optimization needs (PostgreSQL, MySQL, SQL Server)

Core Optimization Workflow

Step 1: Analyze Query Performance

Run execution plan analysis to identify bottlenecks:

PostgreSQL:

sql
EXPLAIN ANALYZE SELECT * FROM users WHERE email = 'user@example.com';

MySQL:

sql
EXPLAIN FORMAT=JSON SELECT * FROM products WHERE category_id = 5;

SQL Server: Use SQL Server Management Studio: Display Estimated Execution Plan (Ctrl+L)

Key Metrics to Monitor:

  • Cost: Estimated resource consumption
  • Rows: Number of rows processed (estimated vs actual)
  • Scan Type: Sequential scan vs index scan
  • Execution Time: Actual time spent on operation

For detailed execution plan interpretation, see references/explain-guide.md.

Step 2: Identify Optimization Opportunities

Common Red Flags:

IndicatorProblemSolution
Seq Scan / Table ScanFull table scan on large tableAdd index on filter columns
High row countProcessing excessive rowsAdd WHERE filter or index
Nested Loop with large outer tableInefficient join algorithmIndex join columns
Correlated subquerySubquery executes per rowRewrite as JOIN or EXISTS
Sort operation on large result setExpensive sortingAdd index matching ORDER BY

For scan type interpretation, see references/scan-types.md.

Step 3: Apply Indexing Strategies

Index Decision Framework:

Is column used in WHERE, JOIN, ORDER BY, or GROUP BY?
├─ YES → Is column selective (many unique values)?
│  ├─ YES → Is table frequently queried?
│  │  ├─ YES → ADD INDEX
│  │  └─ NO → Consider based on query frequency
│  └─ NO (low selectivity) → Skip index
└─ NO → Skip index

Index Types by Use Case:

PostgreSQL:

  • B-tree (default): General-purpose, supports <, ≤, =, ≥, >, BETWEEN, IN
  • Hash: Equality comparisons only (=)
  • GIN: Full-text search, JSONB, arrays
  • GiST: Spatial data, geometric types
  • BRIN: Very large tables with naturally ordered data

MySQL:

  • B-tree (default): General-purpose index
  • Full-text: Text search on VARCHAR/TEXT columns
  • Spatial: Spatial data types

SQL Server:

  • Clustered: Table data sorted by index (one per table)
  • Non-clustered: Separate index structure (multiple allowed)

For comprehensive indexing guidance, see references/indexing-decisions.md and references/index-types.md.

Step 4: Design Composite Indexes

For queries filtering on multiple columns, use composite indexes:

Column Order Matters:

  1. Equality filters first (most selective)
  2. Additional equality filters (by selectivity)
  3. Range filters or ORDER BY (last)

Example:

sql
-- Query pattern
SELECT * FROM orders
WHERE customer_id = 123 AND status = 'shipped'
ORDER BY created_at DESC
LIMIT 10;

-- Optimal composite index
CREATE INDEX idx_orders_customer_status_created
ON orders (customer_id, status, created_at DESC);

For composite index design patterns, see references/composite-indexes.md.

Step 5: Rewrite Inefficient Queries

Common Anti-Patterns to Avoid:

1. SELECT * (Over-fetching)

sql
-- ❌ Bad: Fetches all columns
SELECT * FROM users WHERE id = 1;

-- ✅ Good: Fetch only needed columns
SELECT id, name, email FROM users WHERE id = 1;

2. N+1 Queries

sql
-- ❌ Bad: 1 + N queries
SELECT * FROM users LIMIT 100;
-- Then in loop: SELECT * FROM posts WHERE user_id = ?;

-- ✅ Good: Single JOIN
SELECT users.*, posts.id AS post_id, posts.title
FROM users
LEFT JOIN posts ON users.id = posts.user_id;

3. Non-Sargable Queries (functions on indexed columns)

sql
-- ❌ Bad: Function prevents index usage
SELECT * FROM orders WHERE YEAR(created_at) = 2025;

-- ✅ Good: Sargable range condition
SELECT * FROM orders
WHERE created_at >= '2025-01-01' AND created_at < '2026-01-01';

4. Correlated Subqueries

sql
-- ❌ Bad: Subquery executes per row
SELECT name,
  (SELECT COUNT(*) FROM orders WHERE orders.user_id = users.id)
FROM users;

-- ✅ Good: JOIN with GROUP BY
SELECT users.name, COUNT(orders.id) AS order_count
FROM users
LEFT JOIN orders ON users.id = orders.user_id
GROUP BY users.id, users.name;

For complete anti-pattern reference, see references/anti-patterns.md. For efficient query patterns, see references/efficient-patterns.md.

Quick Reference Tables

Index Selection Guide

Query PatternIndex TypeExample
WHERE column = valueSingle-column B-treeCREATE INDEX ON table (column)
WHERE col1 = ? AND col2 = ?Composite B-treeCREATE INDEX ON table (col1, col2)
WHERE text_col LIKE '%word%'Full-text (GIN/Full-text)CREATE INDEX ON table USING GIN (to_tsvector('english', text_col))
WHERE geom && boxSpatial (GiST)CREATE INDEX ON table USING GIST (geom)
WHERE json_col @> '{"key":"value"}'JSONB (GIN)CREATE INDEX ON table USING GIN (json_col)

Join Optimization Checklist

  • Index foreign key columns on both sides of JOIN
  • Order joins starting with table returning fewest rows
  • Use INNER JOIN when possible (more efficient than OUTER JOIN)
  • Avoid joining more than 5 tables (break into CTEs or subqueries)
  • Consider denormalization for frequently joined tables in read-heavy systems

Execution Plan Performance Targets

Scan TypePerformanceWhen Acceptable
Index-Only ScanBestAlways preferred
Index ScanExcellentSmall-medium result sets
Bitmap Heap ScanGoodMedium result sets (PostgreSQL)
Sequential ScanPoorOnly for small tables (<1000 rows) or full table queries
Table ScanPoorOnly for small tables or unavoidable full scans

Database-Specific Optimizations

PostgreSQL-Specific Features

Partial Indexes (index subset of rows):

sql
CREATE INDEX idx_active_users_login
ON users (last_login)
WHERE status = 'active';

Expression Indexes (index computed values):

sql
CREATE INDEX idx_users_email_lower
ON users (LOWER(email));

Covering Indexes (avoid heap access):

sql
CREATE INDEX idx_users_email_covering
ON users (email) INCLUDE (id, name);

For comprehensive PostgreSQL optimization, see references/postgresql.md.

MySQL-Specific Features

Index Hints (override optimizer):

sql
SELECT * FROM orders USE INDEX (idx_orders_customer)
WHERE customer_id = 123;

Storage Engine Selection:

  • InnoDB (default): Transactional, row-level locks, clustered primary key
  • MyISAM: Faster reads, no transactions, table-level locks

For comprehensive MySQL optimization, see references/mysql.md.

SQL Server-Specific Features

Query Store (track query performance over time):

sql
ALTER DATABASE YourDatabase SET QUERY_STORE = ON;

Execution Plan Warnings:

  • Look for yellow exclamation marks in graphical execution plans
  • Thick arrows indicate high row counts

For comprehensive SQL Server optimization, see references/sqlserver.md.

Advanced Optimization Techniques

Common Table Expressions (CTEs)

Break complex queries into readable, maintainable parts:

sql
WITH active_customers AS (
  SELECT id, name FROM customers WHERE status = 'active'
),
recent_orders AS (
  SELECT customer_id, COUNT(*) as order_count
  FROM orders
  WHERE created_at > NOW() - INTERVAL '30 days'
  GROUP BY customer_id
)
SELECT ac.name, COALESCE(ro.order_count, 0) as orders
FROM active_customers ac
LEFT JOIN recent_orders ro ON ac.id = ro.customer_id;

EXISTS vs IN for Subqueries

Use EXISTS for better performance with large datasets:

sql
-- ✅ Good: EXISTS stops at first match
SELECT * FROM users
WHERE EXISTS (SELECT 1 FROM orders WHERE orders.user_id = users.id);

-- ❌ Less efficient: IN builds full list
SELECT * FROM users
WHERE id IN (SELECT user_id FROM orders);

Denormalization Decision Framework

Consider denormalization when:

  • Query joins 3+ tables frequently
  • Data is relatively static (infrequent updates)
  • Read performance is critical
  • Write overhead is acceptable

Denormalization Strategies:

  1. Duplicate columns: Copy foreign key data into main table
  2. Summary tables: Pre-aggregate data
  3. Materialized views: Database-maintained denormalized views
  4. Application caching: Redis/Memcached for frequently accessed data

Optimization Workflow Example

Scenario: API endpoint taking 2 seconds to load

Step 1: Identify Slow Query

Use APM/observability tools to identify database query causing delay

Step 2: Run EXPLAIN ANALYZE

sql
EXPLAIN ANALYZE SELECT * FROM orders
WHERE customer_id = 123
ORDER BY created_at DESC
LIMIT 10;

Step 3: Analyze Output

Seq Scan on orders (cost=0.00..2500.00 rows=10)
  Filter: (customer_id = 123)
  Rows Removed by Filter: 99990

Problem: Sequential scan filtering 99,990 rows

Step 4: Add Composite Index

sql
CREATE INDEX idx_orders_customer_created
ON orders (customer_id, created_at DESC);

Step 5: Verify Improvement

sql
EXPLAIN ANALYZE SELECT * FROM orders
WHERE customer_id = 123
ORDER BY created_at DESC
LIMIT 10;
Index Scan using idx_orders_customer_created (cost=0.42..12.44 rows=10)
  Index Cond: (customer_id = 123)

Result: 200x faster (2000ms → 10ms)

Monitoring and Maintenance

Regular Optimization Tasks:

  • Review slow query logs weekly
  • Update database statistics regularly (ANALYZE in PostgreSQL, UPDATE STATISTICS in SQL Server)
  • Monitor index usage (drop unused indexes)
  • Archive old data to keep tables manageable
  • Review execution plans for critical queries quarterly

PostgreSQL Statistics Update:

sql
ANALYZE table_name;

MySQL Statistics Update:

sql
ANALYZE TABLE table_name;

SQL Server Statistics Update:

sql
UPDATE STATISTICS table_name;

Related Skills

  • databases-relational: Schema design and database fundamentals
  • observability: Performance monitoring and slow query detection
  • api-patterns: API-level optimization (pagination, caching)
  • performance-engineering: Application performance profiling

Additional Resources

For comprehensive documentation, reference these files:

  • references/explain-guide.md - Detailed EXPLAIN plan interpretation
  • references/scan-types.md - Scan type meanings and performance implications
  • references/indexing-decisions.md - When and how to add indexes
  • references/index-types.md - Database-specific index types
  • references/composite-indexes.md - Multi-column index design
  • references/anti-patterns.md - Common anti-patterns with solutions
  • references/efficient-patterns.md - Efficient query patterns
  • references/postgresql.md - PostgreSQL-specific optimizations
  • references/mysql.md - MySQL-specific optimizations
  • references/sqlserver.md - SQL Server-specific optimizations

For working SQL examples, see examples/ directory.

附带文件

技能加载后,模型会按需读取这些文件。它们仅作为可读文件提供,绝不会被执行。

常见问题

Optimizing Sql AI 技能有什么作用?

Optimize SQL query performance through EXPLAIN analysis, indexing strategies, and query rewriting for PostgreSQL, MySQL, and SQL Server. Use when debugging slow queries, analyzing execution plans, or improving database performance.

为什么在 TypingMind 中使用 Optimizing Sql?

因为您只需安装一次,就能搭配任何模型使用。Optimizing Sql 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型。您甚至可以在聊天中途切换模型,而不会影响技能的正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 Optimizing Sql?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/ancoleman/ai-design-components/tree/main/skills/optimizing-sql。TypingMind 会读取其中的 SKILL.md,打包相关文件,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Optimizing Sql?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

Optimizing Sql 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以将它与 Optimizing Sql 搭配使用。GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等模型都可以通过您自己的 API 密钥接入 TypingMind。

Optimizing Sql AI 技能免费吗?

是的。ancoleman 已在 GitHub 上根据 MIT 许可证发布了该技能。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇