
Database Query Optimization
- 525 installs
- 305 repo stars
- Updated March 4, 2026
- aj-geddes/useful-ai-prompts
database-query-optimization is a Claude Code skill that diagnoses and accelerates slow SQL queries using EXPLAIN ANALYZE, indexing strategies, and execution plan review for developers who need to cut database latency and
About
database-query-optimization is a structured performance skill from aj-geddes/useful-ai-prompts that walks developers through systematic SQL diagnosis and remediation. The skill covers EXPLAIN ANALYZE interpretation, indexing strategies, efficient query rewrites, and execution plan review to reduce response times and database CPU usage. Reference guides and best-practice sections address slow endpoints, performance regressions, and high-load scenarios common in API-backed applications. Developers reach for database-query-optimization when profiling shows database-bound latency, when new features introduce expensive joins or scans, or when production monitoring flags rising query times. The workflow emphasizes measurable before-and-after plans rather than ad-hoc query tweaks.
- Analyzes EXPLAIN ANALYZE output to distinguish Seq Scan vs Index Scan performance
- Identifies high-variance row estimates, nested loops, and expensive sorts
- Recommends indexing, query rewrites, and caching patterns for production workloads
- Applies to new feature deployments, performance regressions, and scheduled maintenance
- Reduces response times and database CPU usage across Postgres, MySQL and compatible engines
Database Query Optimization by the numbers
- 525 all-time installs (skills.sh)
- Ranked #120 of 911 Databases skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/aj-geddes/useful-ai-prompts --skill database-query-optimizationAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 525 |
|---|---|
| repo stars | ★ 305 |
| Last updated | March 4, 2026 |
| Repository | aj-geddes/useful-ai-prompts ↗ |
How do you optimize slow SQL queries with EXPLAIN?
Systematically diagnose and accelerate slow SQL queries using EXPLAIN ANALYZE, indexing strategies, and execution plan review.
Who is it for?
Backend developers maintaining PostgreSQL, MySQL, or similar relational databases with measurable slow-query bottlenecks.
Skip if: Developers needing NoSQL schema design, full database migration planning, or ORM framework selection without SQL-level tuning.
When should I use this skill?
A developer reports slow API responses, high database CPU, or asks to analyze, index, or rewrite specific SQL queries.
What you get
Execution plans, index recommendations, rewritten queries, and documented performance improvements.
- Optimized SQL statements
- Index recommendations
- Execution plan analysis notes
Files
Database Query Optimization
Table of Contents
Overview
Slow database queries are a common performance bottleneck. Optimization through indexing, efficient queries, and caching dramatically improves application performance.
When to Use
- Slow response times
- High database CPU usage
- Performance regression
- New feature deployment
- Regular maintenance
Quick Start
Minimal working example:
-- Analyze query performance
EXPLAIN ANALYZE
SELECT users.id, users.name, COUNT(orders.id) as order_count
FROM users
LEFT JOIN orders ON users.id = orders.user_id
WHERE users.created_at > '2024-01-01'
GROUP BY users.id, users.name
ORDER BY order_count DESC;
-- Results show:
-- - Seq Scan (slow) vs Index Scan (fast)
-- - Rows: actual vs planned (high variance = bad)
-- - Execution time (milliseconds)
-- Key metrics:
-- - Sequential Scan: Full table read (slow)
-- - Index Scan: Uses index (fast)
-- - Nested Loop: Joins with loops
-- - Sort: In-memory or disk sortReference Guides
Detailed implementations in the references/ directory:
| Guide | Contents |
|---|---|
| Query Analysis | Query Analysis |
| Indexing Strategy | Indexing Strategy |
| Query Optimization Techniques | Query Optimization Techniques |
| Optimization Checklist | Optimization Checklist |
Best Practices
✅ DO
- Follow established patterns and conventions
- Write clean, maintainable code
- Add appropriate documentation
- Test thoroughly before deploying
❌ DON'T
- Skip testing or validation
- Ignore error handling
- Hard-code configuration values
Indexing Strategy
Indexing Strategy
Index Types:
Single Column:
CREATE INDEX idx_users_email ON users(email);
Use: WHERE email = ?
Size: Small, quick to create
Composite Index:
CREATE INDEX idx_orders_user_date
ON orders(user_id, created_at);
Use: WHERE user_id = ? AND created_at > ?
Order: Most selective first
Covering Index:
CREATE INDEX idx_orders_covering
ON orders(user_id) INCLUDE (total_amount);
Benefit: No table lookup needed
Partial Index:
CREATE INDEX idx_active_users
ON users(id) WHERE status = 'active';
Benefit: Smaller, faster
Full Text:
CREATE FULLTEXT INDEX idx_search
ON articles(title, content);
Use: Text search queries
---
Index Rules:
- Create indexes for WHERE conditions
- Create indexes for JOIN columns
- Create indexes for ORDER BY
- Don't over-index (slows writes)
- Monitor index usage
- Remove unused indexes
- Update statistics regularly
- Partial indexes for filtered queries
Missing Index Query:
SELECT object_name, equality_columns
FROM sys.dm_db_missing_index_details
ORDER BY equality_columns;Optimization Checklist
Optimization Checklist
Analysis:
[ ] Run EXPLAIN ANALYZE on slow queries
[ ] Check actual vs estimated rows
[ ] Look for sequential scans
[ ] Identify expensive operations
[ ] Compare execution plans
Indexing:
[ ] Index WHERE columns
[ ] Index JOIN columns
[ ] Index ORDER BY columns
[ ] Check unused indexes
[ ] Remove duplicate indexes
[ ] Create composite indexes strategically
[ ] Analyze index statistics
Query Optimization:
[ ] Remove unnecessary columns (SELECT *)
[ ] Use JOINs instead of subqueries
[ ] Avoid functions in WHERE
[ ] Use wildcards carefully (avoid %)
[ ] Batch operations
[ ] Use LIMIT for result sets
[ ] Archive old data
Caching:
[ ] Implement query caching
[ ] Cache aggregations
[ ] Use Redis for hot data
[ ] Invalidate strategically
Monitoring:
[ ] Track slow queries
[ ] Monitor index usage
[ ] Set up alerts
[ ] Regular statistics update
[ ] Measure improvements
---
Expected Improvements:
With Proper Indexing:
- Sequential Scan → Index Scan
- Response time: 5 seconds → 50ms (100x faster)
- CPU usage: 80% → 20%
- Concurrent users: 100 → 1000
Quick Wins:
- Add index to frequently filtered column
- Fix N+1 queries
- Use LIMIT for large results
- Archive old data
- Expected: 20-50% improvementQuery Analysis
Query Analysis
-- Analyze query performance
EXPLAIN ANALYZE
SELECT users.id, users.name, COUNT(orders.id) as order_count
FROM users
LEFT JOIN orders ON users.id = orders.user_id
WHERE users.created_at > '2024-01-01'
GROUP BY users.id, users.name
ORDER BY order_count DESC;
-- Results show:
-- - Seq Scan (slow) vs Index Scan (fast)
-- - Rows: actual vs planned (high variance = bad)
-- - Execution time (milliseconds)
-- Key metrics:
-- - Sequential Scan: Full table read (slow)
-- - Index Scan: Uses index (fast)
-- - Nested Loop: Joins with loops
-- - Sort: In-memory or disk sortQuery Optimization Techniques
Query Optimization Techniques
# Common optimization patterns
# BEFORE (N+1 queries)
for user in users:
orders = db.query("SELECT * FROM orders WHERE user_id = ?", user.id)
# 1 + N queries
# AFTER (single query with JOIN)
orders = db.query("""
SELECT u.*, o.* FROM users u
LEFT JOIN orders o ON u.id = o.user_id
WHERE u.created_at > ?
""", date_threshold)
# BEFORE (inefficient WHERE)
SELECT * FROM users
WHERE LOWER(email) = LOWER('Test@Example.com')
# Can't use index (function used)
# AFTER (index-friendly)
SELECT * FROM users
WHERE email = 'test@example.com'
# Case-insensitive constraint + index
# BEFORE (wildcard at start)
SELECT * FROM users WHERE email LIKE '%example.com'
# Can't use index (wildcard at start)
# AFTER (wildcard at end)
SELECT * FROM users WHERE email LIKE 'user%'
# Can use index
# BEFORE (slow aggregation)
SELECT user_id, COUNT(*) as cnt
FROM orders
GROUP BY user_id
ORDER BY cnt DESC
LIMIT 10
# AFTER (pre-aggregated)
SELECT user_id, order_count
FROM user_order_stats
WHERE order_count IS NOT NULL
ORDER BY order_count DESC
LIMIT 10#!/bin/bash
# validate-schema.sh - Validate database schema
# Usage: ./validate-schema.sh <schema_file>
set -euo pipefail
SCHEMA_FILE="${{1:?Usage: $0 <schema_file>}}"
echo "Validating schema: $SCHEMA_FILE"
# TODO: Add schema validation
# - Check SQL syntax
# - Verify foreign key references
# - Check index definitions
# - Validate naming conventions
# - Check for missing constraints
echo "Schema validation complete."
-- Migration: [description]
-- Created: [date]
-- TODO: Customize for your migration framework
BEGIN;
-- Up migration
-- TODO: Add schema changes
-- CREATE TABLE IF NOT EXISTS ...
-- ALTER TABLE ...
-- Down migration (rollback)
-- TODO: Add rollback statements
-- DROP TABLE IF EXISTS ...
COMMIT;
Related skills
How it compares
Pick database-query-optimization for hands-on SQL plan and index work rather than general application profiling or ORM configuration guides.
FAQ
What does database-query-optimization analyze first?
database-query-optimization starts with EXPLAIN ANALYZE and execution plan review to locate sequential scans, missing indexes, and expensive joins before proposing index or rewrite changes.
When should developers use database-query-optimization?
database-query-optimization fits slow API endpoints, rising database CPU, and post-release performance regressions where SQL—not application logic—is the suspected bottleneck.