Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

sql-optimization-patterns

БесплатноБез исполняемых скриптовНе проверен

Master SQL query optimization, indexing strategies, and EXPLAIN analysis to dramatically improve database performance and eliminate slow queries. Use when…

onfire7777от 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.

  1. Preserve the query, filter values and environment for the follow-up. EXPLAIN ANALYZE executes the statement. Use a representative read-only query and record whether the cache is cold or warm.
  2. 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.
  3. 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.

  1. Execute the same plan capture against unchanged data. Repeat under comparable cache conditions.
  2. Walk the plan tree and inspect the Seq Scan, Index Scan, Index Only Scan or Bitmap Heap Scan nodes and their index conditions. Compare Actual Rows and Actual Loops, top-level Execution Time and shared block reads/hits. Node times are per loop and parent nodes include child work. Avoid summing node times across the whole tree.
  3. 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 || ' '
Полный SKILL.md на GitHub

Установить sql-optimization-patterns в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

examples/order_history_plan.sql

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), без исполняемых скриптов.

Похожие скиллы

Сравнить sql-optimization-patterns с