sql-optimization-patterns
БесплатноБез исполняемых скриптовНе проверенMaster SQL query optimization, indexing strategies, and EXPLAIN analysis to dramatically improve database performance and eliminate slow queries. Use when…
от onfire7777★ 17 звёзд на GitHubОб этом скилле
SQL Optimization Patterns
Transform slow database queries into lightning-fast operations through systematic optimization, proper indexing, and query plan analysis.
When to Use This Skill
- Debugging slow-running queries
- Designing performant database schemas
- Optimizing application response times
- Reducing database load and costs
- Improving scalability for growing datasets
- Analyzing EXPLAIN query plans
- Implementing efficient indexes
- Resolving N+1 query problems
Core Concepts
1. Query Execution Plans (EXPLAIN)
Understanding EXPLAIN output is fundamental to optimization.
PostgreSQL EXPLAIN:
-- Basic explain
EXPLAIN SELECT * FROM users WHERE email = '[email protected]';
-- With actual execution stats
EXPLAIN ANALYZE
SELECT * FROM users WHERE email = '[email protected]';
-- Verbose output with more details
EXPLAIN (ANALYZE, BUFFERS, VERBOSE)
SELECT u.*, o.order_total
FROM users u
JOIN orders o ON u.id = o.user_id
WHERE u.created_at > NOW() - INTERVAL '30 days';
Key Metrics to Watch:
- Seq Scan: Full table scan (usually slow for large tables)
- Index Scan: Using index (good)
- Index Only Scan: Using index without touching table (best)
- Nested Loop: Join method (okay for small datasets)
- Hash Join: Join method (good for larger datasets)
- Merge Join: Join method (good for sorted data)
- Cost: Estimated query cost (lower is better)
- Rows: Estimated rows returned
- Actual Time: Real execution time
Measure the original PostgreSQL execution plan
Applies when: Capture baseline timings and buffer usage for a slow PostgreSQL read before changing an index or query. Inputs: The actual SELECT, representative filter values, table statistics and a connection to the database being measured. Output: A baseline execution plan with actual rows, loops, scan nodes, elapsed execution time, shared hits and reads.
- Preserve the query, filter values and environment for the follow-up.
EXPLAIN ANALYZEexecutes the statement. Use a representative read-only query and record whether the cache is cold or warm. - Run the same SQL with
EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON). Save the original plan. Read execution time separately from planning time and optimizer cost. A buffer hit reached shared memory. A read required PostgreSQL to load the block, which may still have been in the operating system cache. - Identify the relation, actual and estimated rows, loop count, scan type and index conditions. Large estimate errors or unexpected loops warrant investigation alongside the index design. The example query can be captured with
psql -X -qAt -v ON_ERROR_STOP=1 -f examples/order_history_plan.sql > before.json. PostgreSQL EXPLAIN
Compare the index build with the baseline plan
Applies when: Rerun a PostgreSQL query after an index build and compare scan type, actual time and buffer activity with the original execution plan. Inputs: The saved baseline, the identical read and filter parameters, and the completed, valid index. Output: Before/after scan strategy, index name and conditions, row count, buffer hits/reads and execution-time observations.
- Execute the same plan capture against unchanged data. Repeat under comparable cache conditions.
- Walk the plan tree and inspect the
Seq Scan,Index Scan,Index Only ScanorBitmap Heap Scannodes and their index conditions. CompareActual RowsandActual Loops, top-levelExecution Timeand shared block reads/hits. Node times are per loop and parent nodes include child work. Avoid summing node times across the whole tree. - Verify the result rows independently. Explain a plan change in terms of selectivity and measured work. A sequential scan can be the right result for a small table or a broad filter. PostgreSQL on using EXPLAIN
2. Index Strategies
Indexes are the most powerful optimization tool.
Index Types:
- B-Tree: Default, good for equality and range queries
- Hash: Only for equality (=) comparisons
- GIN: Full-text search, array queries, JSONB
- GiST: Geometric data, full-text search
- BRIN: Block Range INdex for very large tables with correlation
-- Standard B-Tree index
CREATE INDEX idx_users_email ON users(email);
-- Composite index (order matters!)
CREATE INDEX idx_orders_user_status ON orders(user_id, status);
-- Partial index (index subset of rows)
CREATE INDEX idx_active_users ON users(email)
WHERE status = 'active';
-- Expression index
CREATE INDEX idx_users_lower_email ON users(LOWER(email));
-- Covering index (include additional columns)
CREATE INDEX idx_users_email_covering ON users(email)
INCLUDE (name, created_at);
-- Full-text search index
CREATE INDEX idx_posts_search ON posts
USING GIN(to_tsvector('english', title || ' '
Установить sql-optimization-patterns в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл sql-optimization-patterns?
Master SQL query optimization, indexing strategies, and EXPLAIN analysis to dramatically improve database performance and eliminate slow queries. Use when debugging slow queries, designing database schemas, or optimizing application performance.
Как установить скилл sql-optimization-patterns?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл sql-optimization-patterns запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic