
Sql Query Optimization
- 464 installs
- 305 repo stars
- Updated March 4, 2026
- aj-geddes/useful-ai-prompts
sql-query-optimization is an agent skill that helps developers tune slow SQL for production apps by rewriting queries, adding indexes, fixing joins, and reducing latency on API or reporting endpoints backed by Postgres,
About
sql-query-optimization is a skill from aj-geddes/useful-ai-prompts focused on production database performance rather than tutorial SQL. It guides rewriting expensive queries, choosing indexes, correcting join plans, and cutting latency on API handlers and reporting paths that hit Postgres, MySQL, or comparable relational engines. Developers reach for sql-query-optimization when EXPLAIN plans show full scans, nested loops blow up, or p95 endpoint times trace back to specific statements. The skill fits iterative ops work after launch—when schema exists and the goal is measurable query speedups without redesigning the entire data model.
- Index and join strategy guidance
- Explain-plan driven diagnosis
- Latency reduction for hot paths
- Production-safe rewrite patterns
- Works across common SQL engines
Sql Query Optimization by the numbers
- 464 all-time installs (skills.sh)
- Ranked #128 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 sql-query-optimizationAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 464 |
|---|---|
| repo stars | ★ 305 |
| Last updated | March 4, 2026 |
| Repository | aj-geddes/useful-ai-prompts ↗ |
How do you optimize slow SQL queries in production?
Tune slow SQL for production apps: rewrite queries, add indexes, fix joins, and cut latency on reporting or API endpoints backed by Postgres, MySQL, or similar engines.
Who is it for?
Developers debugging slow Postgres or MySQL queries affecting live API or reporting endpoints who need concrete rewrite and index guidance.
Skip if: Greenfield schema design or NoSQL-only data stores where relational index and join tuning patterns do not apply.
When should I use this skill?
Production SQL is slow, EXPLAIN shows bad plans, or API/reporting latency traces to specific relational queries on Postgres or MySQL.
What you get
Rewritten SQL statements, recommended indexes, improved join plans, and measurable latency reductions on targeted endpoints.
- Optimized SQL rewrite
- Index recommendations
- Improved query execution plan
Files
SQL Query Optimization
Table of Contents
Overview
Analyze SQL queries to identify performance bottlenecks and implement optimization techniques. Includes query analysis, indexing strategies, and rewriting patterns for improved performance.
When to Use
- Slow query analysis and tuning
- Query rewriting and refactoring
- Index utilization verification
- Join optimization
- Subquery optimization
- Query plan analysis (EXPLAIN)
- Performance baseline establishment
Quick Start
PostgreSQL:
-- Analyze query plan with execution time
EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)
SELECT u.id, u.email, COUNT(o.id) as order_count
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
WHERE u.created_at > NOW() - INTERVAL '1 year'
GROUP BY u.id, u.email;
-- Check table statistics
SELECT * FROM pg_stats
WHERE tablename = 'users' AND attname = 'created_at';Reference Guides
Detailed implementations in the references/ directory:
| Guide | Contents |
|---|---|
| Analyze Current Performance | Analyze Current Performance |
| Common Optimization Patterns | Common Optimization Patterns |
| Query Rewriting Techniques | Query Rewriting Techniques |
| Batch Operations | Batch Operations |
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
Analyze Current Performance
Analyze Current Performance
PostgreSQL:
-- Analyze query plan with execution time
EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)
SELECT u.id, u.email, COUNT(o.id) as order_count
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
WHERE u.created_at > NOW() - INTERVAL '1 year'
GROUP BY u.id, u.email;
-- Check table statistics
SELECT * FROM pg_stats
WHERE tablename = 'users' AND attname = 'created_at';MySQL:
-- Analyze query plan
EXPLAIN FORMAT=JSON
SELECT u.id, u.email, COUNT(o.id) as order_count
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
WHERE u.created_at > DATE_SUB(NOW(), INTERVAL 1 YEAR)
GROUP BY u.id, u.email;
-- Check table size
SELECT table_name, ROUND(((data_length + index_length) / 1024 / 1024), 2) AS 'Size_MB'
FROM information_schema.tables WHERE table_schema = 'database_name';Batch Operations
Batch Operations
PostgreSQL - Bulk Insert:
-- Inefficient: multiple round trips
INSERT INTO users (email, name) VALUES ('user1@example.com', 'User One');
INSERT INTO users (email, name) VALUES ('user2@example.com', 'User Two');
-- Optimized: single batch
INSERT INTO users (email, name) VALUES
('user1@example.com', 'User One'),
('user2@example.com', 'User Two'),
('user3@example.com', 'User Three')
ON CONFLICT (email) DO UPDATE SET updated_at = NOW();MySQL - Bulk Update:
-- Optimized: bulk update with VALUES clause
UPDATE products p
JOIN (
SELECT id, price FROM product_updates
) AS updates ON p.id = updates.id
SET p.price = updates.price;Common Optimization Patterns
Common Optimization Patterns
PostgreSQL - Index Optimization:
-- Create indexes for frequently filtered columns
CREATE INDEX idx_orders_user_created
ON orders(user_id, created_at DESC)
WHERE status != 'cancelled';
-- Partial indexes for filtered queries
CREATE INDEX idx_active_products
ON products(category_id)
WHERE active = true;
-- Multi-column covering indexes
CREATE INDEX idx_users_email_verified_covering
ON users(email, verified)
INCLUDE (id, name, created_at);MySQL - Index Optimization:
-- Create composite index for multi-column filtering
CREATE INDEX idx_orders_user_created
ON orders(user_id, created_at DESC);
-- Use FULLTEXT index for text search
CREATE FULLTEXT INDEX idx_products_search
ON products(name, description);
-- Prefix indexes for large VARCHAR
CREATE INDEX idx_large_text
ON large_table(text_column(100));Query Rewriting Techniques
Query Rewriting Techniques
PostgreSQL - Window Functions:
-- Inefficient: multiple passes
SELECT p.id, p.name,
(SELECT COUNT(*) FROM orders o WHERE o.product_id = p.id) as order_count,
(SELECT SUM(quantity) FROM order_items oi WHERE oi.product_id = p.id) as total_sold
FROM products p;
-- Optimized: single pass with window functions
SELECT DISTINCT p.id, p.name,
COUNT(*) OVER (PARTITION BY p.id) as order_count,
SUM(oi.quantity) OVER (PARTITION BY p.id) as total_sold
FROM products p
LEFT JOIN order_items oi ON p.id = oi.product_id;MySQL - JOIN Optimization:
-- Inefficient: JOIN after aggregation
SELECT user_id, name, total_orders
FROM (
SELECT u.id as user_id, u.name, COUNT(o.id) as total_orders
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
GROUP BY u.id, u.name
) subquery
WHERE total_orders > 5;
-- Optimized: aggregate with HAVING clause
SELECT u.id, u.name, COUNT(o.id) as total_orders
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
GROUP BY u.id, u.name
HAVING COUNT(o.id) > 5;#!/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
Use sql-query-optimization for statement-level relational tuning; use broader observability skills when latency root cause is outside the database layer.
FAQ
Which databases does sql-query-optimization target?
sql-query-optimization targets production relational engines including Postgres and MySQL, focusing on rewriting queries, adding indexes, and fixing joins that slow API or reporting endpoints.
When should sql-query-optimization be invoked?
sql-query-optimization fits when specific SQL statements drive high latency in production—after identifying slow queries via logs or EXPLAIN—and the goal is targeted rewrites and indexes, not initial schema design.