analyzing-database-indexes
БесплатноЗапускает вложенные скриптыНе проверенProcess use when you need to work with database indexing. This skill provides index design and optimization with comprehensive guidance and automation…
от jeremylongshore★ 2 961 звезда на GitHubОб этом скилле
Database Index Advisor
Overview
Analyze database index usage, identify missing indexes causing sequential scans, detect redundant or unused indexes wasting write performance, and recommend optimal index configurations for PostgreSQL and MySQL.
Prerequisites
- Database credentials with access to
pg_stat_user_indexes,pg_stat_user_tables, andpg_stat_statements(PostgreSQL) orperformance_schemaandsysschema (MySQL) pg_stat_statementsextension enabled for PostgreSQL query statisticspsqlormysqlCLI for executing analysis queries- Representative workload running (analysis during off-peak hours may miss important query patterns)
- At least 24 hours of statistics accumulation since the last
pg_stat_reset()
Instructions
Identify tables with high sequential scan activity (candidates for missing indexes):
- PostgreSQL:
SELECT relname, seq_scan, seq_tup_read, idx_scan, n_live_tup FROM pg_stat_user_tables WHERE seq_scan > 100 AND n_live_tup > 10000 ORDER BY seq_tup_read DESC LIMIT 20 - A table with high
seq_scancount and highseq_tup_readrelative ton_live_tupis scanning most of the table repeatedly
- PostgreSQL:
Find the queries causing sequential scans by correlating with
pg_stat_statements:SELECT query, calls, mean_exec_time, rows FROM pg_stat_statements WHERE query ILIKE '%table_name%' ORDER BY mean_exec_time DESC LIMIT 10- Run
EXPLAIN (ANALYZE, BUFFERS)on the top queries to confirm sequential scan usage
Analyze query WHERE clauses and JOIN conditions to determine which columns need indexes. Extract the filtering columns and their selectivity:
SELECT column_name, n_distinct, correlation FROM pg_stats WHERE tablename = 'target_table'- High
n_distinct(close to row count) indicates good index selectivity correlationclose to 1.0 or -1.0 suggests the column benefits from a B-tree index
Recommend composite indexes for multi-column queries. Follow the equality-first, range-second ordering:
- Place columns used with
=operators first in the index - Place columns used with
>,<,BETWEEN, orLIKE 'prefix%'last - Example:
WHERE status = 'active' AND created_at > '2024-01-01'->CREATE INDEX ON orders (status, created_at)
- Place columns used with
Identify unused indexes wasting write performance:
- PostgreSQL:
SELECT indexrelname, idx_scan, pg_size_pretty(pg_relation_size(indexrelid)) AS index_size FROM pg_stat_user_indexes WHERE idx_scan = 0 AND indexrelname NOT LIKE '%pkey' ORDER BY pg_relation_size(indexrelid) DESC - Indexes with zero scans over a representative period are candidates for removal (verify they are not used by foreign key constraints or unique enforcement)
- PostgreSQL:
Detect redundant indexes where one index is a prefix of another:
- A single-column index on
(customer_id)is redundant if a composite index on(customer_id, created_at)exists, because the composite index serves both single-column and multi-column queries - Generate DROP INDEX recommendations for the redundant subset indexes
- A single-column index on
Evaluate partial indexes for filtered queries. If a query always filters
WHERE status = 'active':CREATE INDEX idx_orders_active ON orders (created_at) WHERE status = 'active'- Partial indexes are smaller and faster than full indexes when the filter eliminates most rows
Consider covering indexes (INCLUDE clause in PostgreSQL 11+) for index-only scans:
CREATE INDEX idx_orders_covering ON orders (customer_id, created_at) INCLUDE (total_amount, status)- The INCLUDE columns are stored in the index leaf pages, enabling index-only scans without heap access
Estimate the impact of each recommendation:
- Index size:
SELECT pg_size_pretty(pg_relation_size('index_name'))for existing similar indexes - Write overhead: each additional index adds approximately 5-15% write latency per INSERT/UPDATE
- Read improvement: compare EXPLAIN plans with and without the proposed index
- Index size:
Generate a prioritized recommendations report with CREATE INDEX and DROP INDEX statements, estimated storage impact, expected query improvement, and write overhead trade-off analysis.
Output
- Missing index recommendations as ready-to-execute CREATE INDEX statements with CONCURRENTLY option
- Unused index report with DROP INDEX candidates and their storage savings
- Redundant index report identifying prefix-overlapping indexes
- Index usage statistics showing scan counts, tuple reads, and sizes for all indexes
- Impact analysis estimating read improvement vs. write overhead for each recommendation
Error Handling
| Error | Cause | Solution |
|---|---|---|
pg_stat_statements not available |
Extension not installed | CREATE EXTENSION pg_stat_statements and add to shared_preload_libraries |
| Index creation blocks writes | CREATE INDEX acquires exclusive lock on the table |
Use CREATE INDEX CONCURRENTLY which does not block writes (takes longer but safe |
Установить analyzing-database-indexes в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadWriteEditGrepGlobBash(psql:*)Bash(mysql:*)Bash(mongosh:*)Вложенные файлы
FAQ
Что делает скилл analyzing-database-indexes?
Process use when you need to work with database indexing. This skill provides index design and optimization with comprehensive guidance and automation. Trigger with phrases like "create indexes", "optimize indexes", or "improve query performance".
Как установить скилл analyzing-database-indexes?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл analyzing-database-indexes запускает скрипты?
Да, скилл несёт исполняемые скрипты. Проверь исходник перед установкой.
Похожие скиллы
frontend-design
Guidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making…
от Anthropicwebapp-testing
Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing…
от Anthropicbrand-guidelines
Applies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. Use it when brand…
от Anthropicweb-artifacts-builder
Suite of tools for creating elaborate, multi-component claude.ai HTML artifacts using modern frontend web technologies (React, Tailwind CSS, shadcn/ui). Use…
от Anthropic