analyzing-query-performance

5
0
Source

Execute use when you need to work with query optimization. This skill provides query performance analysis with comprehensive guidance and automation. Trigger with phrases like "optimize queries", "analyze performance", or "improve query speed".

Install

mkdir -p .claude/skills/analyzing-query-performance && curl -L -o skill.zip "https://mcp.directory/api/skills/download/4112" && unzip -o skill.zip -d .claude/skills/analyzing-query-performance && rm skill.zip

Installs to .claude/skills/analyzing-query-performance

About this skill

Query Performance Analyzer

Overview

Analyze slow database queries using execution plans, wait statistics, and I/O metrics across PostgreSQL, MySQL, and MongoDB. This skill captures EXPLAIN output, identifies sequential scans on large tables, detects missing indexes, measures buffer cache hit ratios, and produces actionable optimization recommendations ranked by expected performance impact.

Prerequisites

  • Database credentials with permissions to run EXPLAIN ANALYZE (PostgreSQL), EXPLAIN FORMAT=JSON (MySQL), or explain() (MongoDB)
  • pg_stat_statements extension enabled for PostgreSQL (provides aggregated query statistics)
  • Access to slow query logs or performance_schema (MySQL)
  • Baseline query execution times for comparison
  • psql, mysql, or mongosh CLI tools installed

Instructions

  1. Identify the slowest queries by examining pg_stat_statements (PostgreSQL): SELECT query, calls, mean_exec_time, total_exec_time FROM pg_stat_statements ORDER BY mean_exec_time DESC LIMIT 20. For MySQL, enable and query the slow query log or performance_schema.events_statements_summary_by_digest.

  2. Run EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) on each slow query in PostgreSQL, or EXPLAIN ANALYZE FORMAT=JSON in MySQL. Capture the full execution plan including actual row counts, loop iterations, and buffer usage.

  3. Analyze the execution plan for these red flags:

    • Sequential scans on tables with >10,000 rows (indicates missing index)
    • Nested loop joins with high outer row counts (consider hash join or merge join)
    • Sort operations without index support (adding a covering index eliminates the sort)
    • High rows_removed_by_filter relative to rows (predicate not selective enough)
    • Bitmap heap scans with high recheck rate (index selectivity too low)
  4. Check buffer cache performance: SELECT heap_blks_read, heap_blks_hit, heap_blks_hit::float / (heap_blks_hit + heap_blks_read) AS cache_hit_ratio FROM pg_statio_user_tables WHERE relname = 'table_name'. A ratio below 0.95 suggests the working set exceeds available shared_buffers.

  5. Evaluate index usage with SELECT indexrelname, idx_scan, idx_tup_read, idx_tup_fetch FROM pg_stat_user_indexes WHERE schemaname = 'public' ORDER BY idx_scan ASC. Indexes with zero scans are unused and waste write performance.

  6. Check for table bloat using SELECT relname, n_live_tup, n_dead_tup, n_dead_tup::float / GREATEST(n_live_tup, 1) AS dead_ratio FROM pg_stat_user_tables WHERE n_dead_tup > 1000 ORDER BY dead_ratio DESC. A dead tuple ratio above 0.2 indicates the table needs VACUUM.

  7. For each identified issue, generate a specific recommendation: CREATE INDEX statement with the exact columns, query rewrite suggestions, or configuration parameter adjustments.

  8. Estimate the performance impact of each recommendation by comparing the EXPLAIN plan before and after applying the change on a staging database or by analyzing the expected row reduction from new indexes.

  9. Prioritize recommendations by impact-to-effort ratio: index additions (high impact, low effort) before query rewrites (medium impact, medium effort) before schema changes (high impact, high effort).

  10. Generate a performance analysis report with before/after execution plans, estimated improvements, and implementation priority ranking.

Output

  • Slow query inventory with execution frequency, mean/P95 duration, and total time consumed
  • Annotated execution plans highlighting sequential scans, sort bottlenecks, and join inefficiencies
  • Index recommendations as ready-to-execute CREATE INDEX statements with expected impact
  • Query rewrite suggestions with original and optimized SQL side by side
  • Buffer cache analysis with shared_buffers sizing recommendations
  • Performance report ranking all findings by severity and implementation priority

Error Handling

ErrorCauseSolution
EXPLAIN ANALYZE takes too long on productionQuery modifies data or runs for minutesUse EXPLAIN without ANALYZE for estimated plans; run EXPLAIN ANALYZE on staging with representative data
pg_stat_statements not availableExtension not installed or not in shared_preload_librariesRun CREATE EXTENSION pg_stat_statements; add to shared_preload_libraries in postgresql.conf and restart
Execution plan differs between staging and productionDifferent data distribution, statistics, or configurationRun ANALYZE on staging tables to update statistics; match work_mem, random_page_cost, and effective_cache_size settings
Index recommendation causes slow writesToo many indexes on a write-heavy tableLimit indexes to 5-7 per table; use partial indexes to reduce scope; consider covering indexes to replace multiple single-column indexes
Query plan uses wrong indexStale statistics or cost model miscalculationRun ANALYZE table_name to refresh statistics; adjust random_page_cost for SSD storage; use SET enable_seqscan = off to test index plans

Examples

Optimizing a dashboard aggregate query: A query computing daily revenue with GROUP BY date and JOIN across orders and line_items takes 12 seconds. EXPLAIN reveals a sequential scan on line_items (5M rows). Adding a composite index on (order_id, created_at) with INCLUDE (amount) reduces execution to 200ms by enabling an index-only scan.

Diagnosing N+1 query pattern: Application loads a list page showing 50 products, each with a separate query for category name. pg_stat_statements reveals SELECT name FROM categories WHERE id = $1 called 50 times per page load. Resolution: rewrite as a single JOIN query or implement eager loading in the ORM.

Identifying bloated table causing cache misses: Buffer cache hit ratio drops to 0.78 on the sessions table. Investigation reveals 80% dead tuples due to aggressive INSERT/DELETE cycling without autovacuum tuning. Setting autovacuum_vacuum_scale_factor = 0.01 and running VACUUM FULL restores cache hit ratio to 0.99.

Resources

svg-icon-generator

jeremylongshore

Svg Icon Generator - Auto-activating skill for Visual Content. Triggers on: svg icon generator, svg icon generator Part of the Visual Content skill category.

6814

d2-diagram-creator

jeremylongshore

D2 Diagram Creator - Auto-activating skill for Visual Content. Triggers on: d2 diagram creator, d2 diagram creator Part of the Visual Content skill category.

2212

performing-penetration-testing

jeremylongshore

This skill enables automated penetration testing of web applications. It uses the penetration-tester plugin to identify vulnerabilities, including OWASP Top 10 threats, and suggests exploitation techniques. Use this skill when the user requests a "penetration test", "pentest", "vulnerability assessment", or asks to "exploit" a web application. It provides comprehensive reporting on identified security flaws.

379

designing-database-schemas

jeremylongshore

Design and visualize efficient database schemas, normalize data, map relationships, and generate ERD diagrams and SQL statements.

978

performing-security-audits

jeremylongshore

This skill allows Claude to conduct comprehensive security audits of code, infrastructure, and configurations. It leverages various tools within the security-pro-pack plugin, including vulnerability scanning, compliance checking, cryptography review, and infrastructure security analysis. Use this skill when a user requests a "security audit," "vulnerability assessment," "compliance review," or any task involving identifying and mitigating security risks. It helps to ensure code and systems adhere to security best practices and compliance standards.

86

django-view-generator

jeremylongshore

Generate django view generator operations. Auto-activating skill for Backend Development. Triggers on: django view generator, django view generator Part of the Backend Development skill category. Use when working with django view generator functionality. Trigger with phrases like "django view generator", "django generator", "django".

15

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

642969

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

590705

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

318398

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

339397

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

451339

fastapi-templates

wshobson

Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.

304231

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.