Command Palette

Search for a command to run...

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

sql-optimization

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

SQL query optimization patterns including EXPLAIN plan analysis, index strategies, query rewriting, and N+1 query prevention. Use when optimizing slow…

stefan-jansenот stefan-jansen★ 101 звезда на GitHub28 установок в других каталогах

Об этом скилле

SQL Query Optimization Patterns

Comprehensive guide to optimizing SQL queries for performance, including EXPLAIN plan analysis, index design strategies, query rewriting patterns, and N+1 query detection. Works across PostgreSQL, MySQL, and SQLite.


Quick Reference

When to use this skill:

  • Slow database queries (>100ms for simple queries, >1s for complex)
  • High database CPU usage
  • Analyzing EXPLAIN plans
  • Designing database indexes
  • Debugging N+1 query problems
  • Optimizing JOIN operations
  • Reducing table scans

Common triggers:

  • "This query is too slow"
  • "How do I optimize this SQL"
  • "What indexes should I add"
  • "Explain this EXPLAIN plan"
  • "Fix N+1 queries"
  • "Database CPU at 100%"

Typical improvements:

  • 3 seconds → 50ms (60x faster)
  • Full table scan → Index scan
  • 1000 queries → 2 queries (N+1 elimination)

Part 1: Understanding EXPLAIN Plans

Reading PostgreSQL EXPLAIN

EXPLAIN ANALYZE
SELECT u.name, p.title
FROM users u
JOIN posts p ON u.id = p.user_id
WHERE u.created_at > '2024-01-01'
ORDER BY p.created_at DESC
LIMIT 10;

Key Metrics to Watch:

  • Seq Scan (bad): Full table scan, reads every row
  • Index Scan (good): Uses index, reads only needed rows
  • Cost: Estimated computational cost (lower is better)
  • Actual time: Real execution time in milliseconds
  • Rows: Number of rows processed at each step

Bad EXPLAIN Example

Seq Scan on users u  (cost=0.00..1234.00 rows=1000 width=50)
                     (actual time=0.123..45.678 rows=950 loops=1)
  Filter: (created_at > '2024-01-01'::date)
  Rows Removed by Filter: 50000
Planning Time: 0.234 ms
Execution Time: 3456.789 ms

Problems:

  • Seq Scan: Reading entire table (50,950 rows)
  • Rows Removed by Filter: Filtering after reading (wasteful)
  • Execution Time: 3.5 seconds (way too slow)

Good EXPLAIN Example (After Index)

Index Scan using users_created_at_idx on users u
  (cost=0.29..123.45 rows=950 width=50)
  (actual time=0.012..3.456 rows=950 loops=1)
  Index Cond: (created_at > '2024-01-01'::date)
Planning Time: 0.123 ms
Execution Time: 4.567 ms

Improvements:

  • Index Scan: Using index (only reads needed rows)
  • Index Cond: Filtering during index scan (efficient)
  • Execution Time: 4.5ms (750x faster!)

Part 2: Index Design Strategies

When to Add an Index

✅ Add index when:

  • Column frequently in WHERE clauses
  • Column frequently in JOIN conditions
  • Column frequently in ORDER BY
  • Query does Seq Scan on large table (>10K rows)
  • Query execution time >100ms

❌ Don't add index when:

  • Table has <1000 rows (Seq Scan is fast enough)
  • Column rarely queried
  • Column has very low cardinality (e.g., boolean with 50/50 distribution)
  • Table has heavy writes (indexes slow down INSERTs/UPDATEs)

Single-Column Indexes

-- Create index on frequently queried column
CREATE INDEX idx_users_email ON users(email);
CREATE INDEX idx_posts_user_id ON posts(user_id);
CREATE INDEX idx_orders_created_at ON orders(created_at);

Query that benefits:

-- Before index: Seq Scan (3000ms)
-- After index: Index Scan (5ms)
SELECT * FROM users WHERE email = '[email protected]';

Composite Indexes (Multi-Column)

Order matters! Put most selective column first.

-- Good: Specific to general
CREATE INDEX idx_orders_user_status ON orders(user_id, status, created_at);

-- Query that uses all columns
SELECT * FROM orders
WHERE user_id = 123
  AND status = 'pending'
ORDER BY created_at DESC;

Index usage rules:

-- ✅ Uses index (matches from left)
WHERE user_id = 123
WHERE user_id = 123 AND status = 'pending'
WHERE user_id = 123 AND status = 'pending' AND created_at > '2024-01-01'

-- ❌ Doesn't use index (skips first column)
WHERE status = 'pending'
WHERE created_at > '2024-01-01'

Partial Indexes (Filtered)

Index only subset of rows (smaller, faster):

-- Only index active users
CREATE INDEX idx_users_active_email
ON users(email)
WHERE status = 'active';

-- Query that uses partial index
SELECT * FROM users
WHERE email = '[email protected]'
  AND status = 'active';  -- Must include filter condition!

Benefits:

  • Smaller index (faster scans, less storage)
  • Only indexes rows you actually query
  • Great for status fields with skewed distribution

Covering Indexes (INCLUDE)

Include columns in index to avoid table access:

-- Postgres: INCLUDE clause
CREATE INDEX idx_users_email_covering
ON users(email)
INCLUDE (name, created_at);

-- Query doesn't need to access table (all data in index)
SELECT name, created_at FROM users WHERE email = '[email protected]';

Benefit: Index-Only Scan (even faster than Index Scan)


Part 3: Query Rewriting Patterns

Problem 1: SELECT * (Fetching Unnecessary Data)

❌ Bad (fetches all columns):

SELECT * FROM users WHERE id = 123;

✅ Good (fetches only needed columns): ```sq

Полный SKILL.md на GitHub

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

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

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

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

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

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

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

FAQ

Что делает скилл sql-optimization?

SQL query optimization patterns including EXPLAIN plan analysis, index strategies, query rewriting, and N+1 query prevention. Use when optimizing slow database queries, analyzing query performance, designing indexes, or debugging database bottlenecks. Works with PostgreSQL, MySQL, SQLite, and other SQL databases. Typical improvements: 10x-1000x query speedup.

Как установить скилл sql-optimization?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл sql-optimization запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

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

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