database-optimization-sh-22bpy4
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 "database-optimization-sh-22bpy4" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-e841fc4e7382adfafec7694f2e66f3e01eb1ddef53d99cbc9ec4847392eebe99. Verify the upstream source and version against https://skillhub.cn/skills/user_3c6cb52e/database-optimization-sh-22bpy4 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
Dedicated database optimization skill to help an AI agent efficiently carry out tasks and workflows related to database optimization.
Introduction source: third_party · user_3c6cb52e · 1.0.0 Reference
SkillPi interpretation
- Tasks
- Always run `EXPLAIN ANALYZE` before optimizing. Read the output bottom-up.
- Testing
- Not tested
Browse files
Frontmatter
name: 数据库优化
slug: database-optimization
version: 1.0.0
displayName: 数据库优化
description: >
数据库优化专用技能,帮助AI Agent高效完成相关任务。
summary: "数据库优化专用技能,帮助AI Agent高效完成相关任务。"
license: MIT
category: 开发者工具
framework:
- Claude Code
- Codex
- Hermes Agent
- OpenClaw
- QClaw
- WorkBuddy
platform: multi-platform
homepage: "https://github.com/1991513ccie-png"
repository: "https://github.com/1991513ccie-png"Database Optimization
EXPLAIN Analysis
Always run EXPLAIN ANALYZE before optimizing. Read the output bottom-up.
-- PostgreSQL
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT) SELECT ...;
-- MySQL
EXPLAIN ANALYZE SELECT ...;
Key metrics to watch:
- Seq Scan on large tables = missing index
- Nested Loop with high row count = consider hash/merge join
- Sort without index = add index on sort column
- Rows estimated vs actual divergence = stale statistics, run
ANALYZE
Index Strategies
B-tree (default, most cases)
CREATE INDEX idx_users_email ON users (email);
CREATE INDEX idx_orders_user_date ON orders (user_id, created_at DESC);
Use for: equality, range queries, sorting. Column order matters in composite indexes: put equality columns first, then range/sort columns.
Partial Index (PostgreSQL)
CREATE INDEX idx_orders_pending ON orders (created_at)
WHERE status = 'pending';
Use when queries always filter on a specific condition. Dramatically smaller than full indexes.
GIN (PostgreSQL - arrays, JSONB, full-text)
CREATE INDEX idx_products_tags ON products USING GIN (tags);
CREATE INDEX idx_docs_search ON documents USING GIN (to_tsvector('english', content));
GiST (PostgreSQL - spatial, range types)
CREATE INDEX idx_locations_point ON locations USING GiST (coordinates);
CREATE INDEX idx_events_period ON events USING GiST (tsrange(start_at, end_at));
Covering Index (index-only scans)
-- PostgreSQL
CREATE INDEX idx_users_email_name ON users (email) INCLUDE (name);
-- MySQL
CREATE INDEX idx_users_email_name ON users (email, name);
N+1 Query Detection
Symptom: 1 query to fetch parent + N queries for each child.
# BAD: N+1
users = db.query(User).all()
for user in users:
print(user.orders) # triggers query per user
# GOOD: eager load
users = db.query(User).options(joinedload(User.orders)).all()
// BAD: N+1
const users = await User.findAll();
for (const user of users) {
const orders = await Order.findAll({ where: { userId: user.id } });
}
// GOOD: batch load
const users = await User.findAll({ include: [Order] });
Detection: enable query logging, count queries per request. More than 10 queries for a single endpoint is a red flag.
Connection Pooling
Rule of thumb: pool_size = (core_count * 2) + disk_count
Typical web app: 10-20 connections per app instance
PostgreSQL:
- Use PgBouncer in transaction mode for serverless/high-connection scenarios
- Set
idle_in_transaction_session_timeout = '30s' - Monitor with
pg_stat_activity
MySQL:
- Set
max_connectionsbased on available RAM (each connection uses ~10MB) - Use ProxySQL for connection multiplexing
- Monitor with
SHOW PROCESSLIST
Read Replicas
- Route all
SELECTqueries to replicas - Route all writes to primary
- Account for replication lag (typically 10-100ms)
- Never read-after-write from a replica; use primary for consistency-critical reads
- Use connection-level routing, not query-level
# SQLAlchemy read replica routing
class RoutingSession(Session):
def get_bind(self, mapper=None, clause=None):
if self._flushing or self.is_modified():
return engines["primary"]
return engines["replica"]
Partition Strategies
Range Partitioning (time-series data)
-- PostgreSQL
CREATE TABLE events (
id bigint GENERATED ALWAYS AS IDENTITY,
created_at timestamptz NOT NULL,
data jsonb
) PARTITION BY RANGE (created_at);
CREATE TABLE events_2025_q1 PARTITION OF events
FOR VALUES FROM ('2025-01-01') TO ('2025-04-01');
CREATE TABLE events_2025_q2 PARTITION OF events
FOR VALUES FROM ('2025-04-01') TO ('2025-07-01');
Hash Partitioning (even distribution)
CREATE TABLE sessions (
id uuid PRIMARY KEY,
user_id bigint NOT NULL
) PARTITION BY HASH (user_id);
CREATE TABLE sessions_0 PARTITION OF sessions FOR VALUES WITH (MODULUS 4, REMAINDER 0);
CREATE TABLE sessions_1 PARTITION OF sessions FOR VALUES WITH (MODULUS 4, REMAINDER 1);
Partition when tables exceed 50-100GB or when you need to drop old data quickly.
Query Optimization Checklist
- Run
EXPLAIN ANALYZEand read the plan - Check for sequential scans on tables with >10K rows
- Verify index usage (check
idx_scaninpg_stat_user_indexes) - Look for implicit type casts that prevent index use
- Replace
SELECT *with specific columns - Add
LIMITto queries that only need a subset - Use
EXISTSinstead ofCOUNT(*) > 0 - Batch
INSERT/UPDATEoperations (500-1000 rows per batch) - Avoid functions on indexed columns in
WHEREclauses - Monitor slow query log (pg:
log_min_duration_statement = 100)
Dangerous Patterns
LIKE '%term%'on unindexed columns (use full-text search instead)ORDER BY RANDOM()(useTABLESAMPLEor application-level randomization)SELECT DISTINCTmasking a join problem- Missing
WHEREonUPDATE/DELETE(always verify withSELECTfirst) - Long-running transactions holding locks
- Using
OFFSETfor deep pagination (use keyset/cursor pagination instead)
Current listing version
1.0.0
Safety and assessment details
Quality assessment
Out of 100 · Assessment report from SkillPi LAB.
Highlights
- 提供数据库优化的完整方法论,涵盖 EXPLAIN 分析、索引策略、N+1 查询检测、连接池、读写分离、分区策略等
- 内容专业且实用,面向开发者高频刚需场景,显著提升数据库性能调优效率
Highlights
- description 明确为'数据库优化专用技能',触发词精准,边界清晰,无歧义
Highlights
- 文档结构清晰,分章节组织,每部分有具体示例和代码片段,frontmatter 完整
Highlights
- SQL 示例语法正确,涵盖 PostgreSQL 和 MySQL,参数合理,提供了监控和检测建议
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.
Domains or addresses referenced in the document
These addresses may be documentation links or examples, not an approved network allowlist. Verify actual destinations and outgoing data before use.
- github.com
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.