Master SQL query optimization, indexing strategies
SQL optimization patterns

Master SQL query optimization, indexing strategies, and EXPLAIN analysis to dramatically improve database performance and eliminate slow queries. Use when debugging slow queries, designing database schemas, or optimizing application…
--- name: sql-optimization-patterns description: Master SQL query optimization, indexing strategies, and EXPLAIN analysis to dramatically improve database performance and eliminate slow queries. Use when debugging slow queries, designing database schemas, or optimizing application performance. --- # SQL Optimization Patterns Transform slow database queries into lightning-fast operations through systematic optimization, proper indexing, and query plan analysis. ## When to Use This Skill - Debugging slow-running queries - Designing performant database schemas - Optimizing application response times - Reducing database load and costs - Improving scalability for growing datasets - Analyzing EXPLAIN query plans - Implementing efficient indexes
Overview
Transform slow database queries into lightning-fast operations through systematic optimization, proper indexing, and query plan analysis.
Manual install (npx, ZIP)
npx skills add wshobson/agents --skill sql-optimization-patterns -g -a claude-codemkdir -p ~/.claude/skills && curl -sL https://codeload.github.com/wshobson/agents/tar.gz/4236bb91f839 \
| tar -xz -C ~/.claude/skills --strip-components=4 agents-4236bb91f839/plugins/developer-essentials/skills/sql-optimization-patternsNew-Item -ItemType Directory -Force "$HOME\.claude\skills" | Out-Null; Invoke-WebRequest "https://m.agentalley.io/zip/f3b53fb7ee78ad1b59f3/sql-optimization-patterns.zip" -OutFile "$env:TEMP\sql-optimization-patterns.zip"; Expand-Archive "$env:TEMP\sql-optimization-patterns.zip" -DestinationPath "$HOME\.claude\skills" -ForceConnects with Agent Alley MCP · agentalley.io/mcp
Files included
SKILL.md5.8 KBreferences/1 file · 6.7 KB
Read the files here
Show the full text215 lines
SQL Optimization Patterns
Transform slow database queries into lightning-fast operations through systematic optimization, proper indexing, and query plan analysis.
When to Use This Skill
- Debugging slow-running queries
- Designing performant database schemas
- Optimizing application response times
- Reducing database load and costs
- Improving scalability for growing datasets
- Analyzing EXPLAIN query plans
- Implementing efficient indexes
- Resolving N+1 query problems
Core Concepts
1. Query Execution Plans (EXPLAIN)
Understanding EXPLAIN output is fundamental to optimization.
PostgreSQL EXPLAIN:
-- Basic explain
EXPLAIN SELECT * FROM users WHERE email = '[email protected]';
-- With actual execution stats
EXPLAIN ANALYZE
SELECT * FROM users WHERE email = '[email protected]';
-- Verbose output with more details
EXPLAIN (ANALYZE, BUFFERS, VERBOSE)
SELECT u.*, o.order_total
FROM users u
JOIN orders o ON u.id = o.user_id
WHERE u.created_at > NOW() - INTERVAL '30 days';
Key Metrics to Watch:
- Seq Scan: Full table scan (usually slow for large tables)
- Index Scan: Using index (good)
- Index Only Scan: Using index without touching table (best)
- Nested Loop: Join method (okay for small datasets)
- Hash Join: Join method (good for larger datasets)
- Merge Join: Join method (good for sorted data)
- Cost: Estimated query cost (lower is better)
- Rows: Estimated rows returned
- Actual Time: Real execution time
2. Index Strategies
Indexes are the most powerful optimization tool.
Index Types:
- B-Tree: Default, good for equality and range queries
- Hash: Only for equality (=) comparisons
- GIN: Full-text search, array queries, JSONB
- GiST: Geometric data, full-text search
- BRIN: Block Range INdex for very large tables with correlation
-- Standard B-Tree index
CREATE INDEX idx_users_email ON users(email);
-- Composite index (order matters!)
CREATE INDEX idx_orders_user_status ON orders(user_id, status);
-- Partial index (index subset of rows)
CREATE INDEX idx_active_users ON users(email)
WHERE status = 'active';
-- Expression index
CREATE INDEX idx_users_lower_email ON users(LOWER(email));
-- Covering index (include additional columns)
CREATE INDEX idx_users_email_covering ON users(email)
INCLUDE (name, created_at);
-- Full-text search index
CREATE INDEX idx_posts_search ON posts
USING GIN(to_tsvector('english', title || ' ' || body));
-- JSONB index
CREATE INDEX idx_metadata ON events USING GIN(metadata);
3. Query Optimization Patterns
Avoid SELECT *:
-- Bad: Fetches unnecessary columns
SELECT * FROM users WHERE id = 123;
-- Good: Fetch only what you need
SELECT id, email, name FROM users WHERE id = 123;
Use WHERE Clause Efficiently:
-- Bad: Function prevents index usage
SELECT * FROM users WHERE LOWER(email) = '[email protected]';
-- Good: Create functional index or use exact match
CREATE INDEX idx_users_email_lower ON users(LOWER(email));
-- Then:
SELECT * FROM users WHERE LOWER(email) = '[email protected]';
-- Or store normalized data
SELECT * FROM users WHERE email = '[email protected]';
Optimize JOINs:
-- Bad: Cartesian product then filter
SELECT u.name, o.total
FROM users u, orders o
WHERE u.id = o.user_id AND u.created_at > '2024-01-01';
-- Good: Filter before join
SELECT u.name, o.total
FROM users u
JOIN orders o ON u.id = o.user_id
WHERE u.created_at > '2024-01-01';
-- Better: Filter both tables
SELECT u.name, o.total
FROM (SELECT * FROM users WHERE created_at > '2024-01-01') u
JOIN orders o ON u.id = o.user_id;
Detailed patterns and worked examples
Detailed pattern documentation lives in references/details.md. Read that file when the navigation tier above is insufficient.
Best Practices
- Index Selectively: Too many indexes slow down writes
- Monitor Query Performance: Use slow query logs
- Keep Statistics Updated: Run ANALYZE regularly
- Use Appropriate Data Types: Smaller types = better performance
- Normalize Thoughtfully: Balance normalization vs performance
- Cache Frequently Accessed Data: Use application-level caching
- Connection Pooling: Reuse database connections
- Regular Maintenance: VACUUM, ANALYZE, rebuild indexes
-- Update statistics
ANALYZE users;
ANALYZE VERBOSE orders;
-- Vacuum (PostgreSQL)
VACUUM ANALYZE users;
VACUUM FULL users; -- Reclaim space (locks table)
-- Reindex
REINDEX INDEX idx_users_email;
REINDEX TABLE users;
Common Pitfalls
- Over-Indexing: Each index slows down INSERT/UPDATE/DELETE
- Unused Indexes: Waste space and slow writes
- Missing Indexes: Slow queries, full table scans
- Implicit Type Conversion: Prevents index usage
- OR Conditions: Can't use indexes efficiently
- LIKE with Leading Wildcard:
LIKE '%abc'can't use index - Function in WHERE: Prevents index usage unless functional index exists
Monitoring Queries
-- Find slow queries (PostgreSQL)
SELECT query, calls, total_time, mean_time
FROM pg_stat_statements
ORDER BY mean_time DESC
LIMIT 10;
-- Find missing indexes (PostgreSQL)
SELECT
schemaname,
tablename,
seq_scan,
seq_tup_read,
idx_scan,
seq_tup_read / seq_scan AS avg_seq_tup_read
FROM pg_stat_user_tables
WHERE seq_scan > 0
ORDER BY seq_tup_read DESC
LIMIT 10;
-- Find unused indexes (PostgreSQL)
SELECT
schemaname,
tablename,
indexname,
idx_scan,
idx_tup_read,
idx_tup_fetch
FROM pg_stat_user_indexes
WHERE idx_scan = 0
ORDER BY pg_relation_size(indexrelid) DESC;
| 1 | |
| 2 | name sql-optimization-patterns |
| 3 | description Master SQL query optimization, indexing strategies, and EXPLAIN analysis to dramatically improve database performance and eliminate slow queries. Use when debugging slow queries, designing database schemas, or optimizing application performance. |
| 4 | |
| 5 | |
| 6 | # SQL Optimization Patterns |
| 7 | |
| 8 | Transform slow database queries into lightning-fast operations through systematic optimization, proper indexing, and query plan analysis. |
| 9 | |
| 10 | ## When to Use This Skill |
| 11 | |
| 12 | Debugging slow-running queries |
| 13 | Designing performant database schemas |
| 14 | Optimizing application response times |
| 15 | Reducing database load and costs |
| 16 | Improving scalability for growing datasets |
| 17 | Analyzing EXPLAIN query plans |
| 18 | Implementing efficient indexes |
| 19 | Resolving N+1 query problems |
| 20 | |
| 21 | ## Core Concepts |
| 22 | |
| 23 | ### 1. Query Execution Plans (EXPLAIN) |
| 24 | |
| 25 | Understanding EXPLAIN output is fundamental to optimization. |
| 26 | |
| 27 | **PostgreSQL EXPLAIN:** |
| 28 | |
| 29 | |
| 30 | -- Basic explain |
| 31 | EXPLAIN SELECT * FROM users WHERE email = '[email protected]'; |
| 32 | |
| 33 | -- With actual execution stats |
| 34 | EXPLAIN ANALYZE |
| 35 | SELECT * FROM users WHERE email = '[email protected]'; |
| 36 | |
| 37 | -- Verbose output with more details |
| 38 | EXPLAIN (ANALYZE, BUFFERS, VERBOSE) |
| 39 | SELECT u.*, o.order_total |
| 40 | FROM users u |
| 41 | JOIN orders o ON u.id = o.user_id |
| 42 | WHERE u.created_at > NOW() - INTERVAL '30 days'; |
| 43 | |
| 44 | |
| 45 | **Key Metrics to Watch:** |
| 46 | |
| 47 | **Seq Scan**: Full table scan (usually slow for large tables) |
| 48 | **Index Scan**: Using index (good) |
| 49 | **Index Only Scan**: Using index without touching table (best) |
| 50 | **Nested Loop**: Join method (okay for small datasets) |
| 51 | **Hash Join**: Join method (good for larger datasets) |
| 52 | **Merge Join**: Join method (good for sorted data) |
| 53 | **Cost**: Estimated query cost (lower is better) |
| 54 | **Rows**: Estimated rows returned |
| 55 | **Actual Time**: Real execution time |
| 56 | |
| 57 | ### 2. Index Strategies |
| 58 | |
| 59 | Indexes are the most powerful optimization tool. |
| 60 | |
| 61 | **Index Types:** |
| 62 | |
| 63 | **B-Tree**: Default, good for equality and range queries |
| 64 | **Hash**: Only for equality (=) comparisons |
| 65 | **GIN**: Full-text search, array queries, JSONB |
| 66 | **GiST**: Geometric data, full-text search |
| 67 | **BRIN**: Block Range INdex for very large tables with correlation |
| 68 | |
| 69 | |
| 70 | -- Standard B-Tree index |
| 71 | CREATE INDEX idx_users_email ON users(email); |
| 72 | |
| 73 | -- Composite index (order matters!) |
| 74 | CREATE INDEX idx_orders_user_status ON orders(user_id, status); |
| 75 | |
| 76 | -- Partial index (index subset of rows) |
| 77 | CREATE INDEX idx_active_users ON users(email) |
| 78 | WHERE status = 'active'; |
| 79 | |
| 80 | -- Expression index |
| 81 | CREATE INDEX idx_users_lower_email ON users(LOWER(email)); |
| 82 | |
| 83 | -- Covering index (include additional columns) |
| 84 | CREATE INDEX idx_users_email_covering ON users(email) |
| 85 | INCLUDE (name, created_at); |
| 86 | |
| 87 | -- Full-text search index |
| 88 | CREATE INDEX idx_posts_search ON posts |
| 89 | USING GIN(to_tsvector('english', title || ' ' || body)); |
| 90 | |
| 91 | -- JSONB index |
| 92 | CREATE INDEX idx_metadata ON events USING GIN(metadata); |
| 93 | |
| 94 | |
| 95 | ### 3. Query Optimization Patterns |
| 96 | |
| 97 | **Avoid SELECT \*:** |
| 98 | |
| 99 | |
| 100 | -- Bad: Fetches unnecessary columns |
| 101 | SELECT * FROM users WHERE id = 123; |
| 102 | |
| 103 | -- Good: Fetch only what you need |
| 104 | SELECT id, email, name FROM users WHERE id = 123; |
| 105 | |
| 106 | |
| 107 | **Use WHERE Clause Efficiently:** |
| 108 | |
| 109 | |
| 110 | -- Bad: Function prevents index usage |
| 111 | SELECT * FROM users WHERE LOWER(email) = '[email protected]'; |
| 112 | |
| 113 | -- Good: Create functional index or use exact match |
| 114 | CREATE INDEX idx_users_email_lower ON users(LOWER(email)); |
| 115 | -- Then: |
| 116 | SELECT * FROM users WHERE LOWER(email) = '[email protected]'; |
| 117 | |
| 118 | -- Or store normalized data |
| 119 | SELECT * FROM users WHERE email = '[email protected]'; |
| 120 | |
| 121 | |
| 122 | **Optimize JOINs:** |
| 123 | |
| 124 | |
| 125 | -- Bad: Cartesian product then filter |
| 126 | SELECT u.name, o.total |
| 127 | FROM users u, orders o |
| 128 | WHERE u.id = o.user_id AND u.created_at > '2024-01-01'; |
| 129 | |
| 130 | -- Good: Filter before join |
| 131 | SELECT u.name, o.total |
| 132 | FROM users u |
| 133 | JOIN orders o ON u.id = o.user_id |
| 134 | WHERE u.created_at > '2024-01-01'; |
| 135 | |
| 136 | -- Better: Filter both tables |
| 137 | SELECT u.name, o.total |
| 138 | FROM (SELECT * FROM users WHERE created_at > '2024-01-01') u |
| 139 | JOIN orders o ON u.id = o.user_id; |
| 140 | |
| 141 | |
| 142 | ## Detailed patterns and worked examples |
| 143 | |
| 144 | Detailed pattern documentation lives in `references/details.md`. Read that file when the navigation tier above is insufficient. |
| 145 | |
| 146 | ## Best Practices |
| 147 | |
| 148 | **Index Selectively**: Too many indexes slow down writes |
| 149 | **Monitor Query Performance**: Use slow query logs |
| 150 | **Keep Statistics Updated**: Run ANALYZE regularly |
| 151 | **Use Appropriate Data Types**: Smaller types = better performance |
| 152 | **Normalize Thoughtfully**: Balance normalization vs performance |
| 153 | **Cache Frequently Accessed Data**: Use application-level caching |
| 154 | **Connection Pooling**: Reuse database connections |
| 155 | **Regular Maintenance**: VACUUM, ANALYZE, rebuild indexes |
| 156 | |
| 157 | |
| 158 | -- Update statistics |
| 159 | ANALYZE users; |
| 160 | ANALYZE VERBOSE orders; |
| 161 | |
| 162 | -- Vacuum (PostgreSQL) |
| 163 | VACUUM ANALYZE users; |
| 164 | VACUUM FULL users; -- Reclaim space (locks table) |
| 165 | |
| 166 | -- Reindex |
| 167 | REINDEX INDEX idx_users_email; |
| 168 | REINDEX TABLE users; |
| 169 | |
| 170 | |
| 171 | ## Common Pitfalls |
| 172 | |
| 173 | **Over-Indexing**: Each index slows down INSERT/UPDATE/DELETE |
| 174 | **Unused Indexes**: Waste space and slow writes |
| 175 | **Missing Indexes**: Slow queries, full table scans |
| 176 | **Implicit Type Conversion**: Prevents index usage |
| 177 | **OR Conditions**: Can't use indexes efficiently |
| 178 | **LIKE with Leading Wildcard**: `LIKE '%abc'` can't use index |
| 179 | **Function in WHERE**: Prevents index usage unless functional index exists |
| 180 | |
| 181 | ## Monitoring Queries |
| 182 | |
| 183 | |
| 184 | -- Find slow queries (PostgreSQL) |
| 185 | SELECT query, calls, total_time, mean_time |
| 186 | FROM pg_stat_statements |
| 187 | ORDER BY mean_time DESC |
| 188 | LIMIT 10; |
| 189 | |
| 190 | -- Find missing indexes (PostgreSQL) |
| 191 | SELECT |
| 192 | schemaname, |
| 193 | tablename, |
| 194 | seq_scan, |
| 195 | seq_tup_read, |
| 196 | idx_scan, |
| 197 | seq_tup_read / seq_scan AS avg_seq_tup_read |
| 198 | FROM pg_stat_user_tables |
| 199 | WHERE seq_scan > 0 |
| 200 | ORDER BY seq_tup_read DESC |
| 201 | LIMIT 10; |
| 202 | |
| 203 | -- Find unused indexes (PostgreSQL) |
| 204 | SELECT |
| 205 | schemaname, |
| 206 | tablename, |
| 207 | indexname, |
| 208 | idx_scan, |
| 209 | idx_tup_read, |
| 210 | idx_tup_fetch |
| 211 | FROM pg_stat_user_indexes |
| 212 | WHERE idx_scan = 0 |
| 213 | ORDER BY pg_relation_size(indexrelid) DESC; |
| 214 | |
| 215 |
Details
- Updated
- Sep 21, 2026
- License
- MIT
- Stars on the repo
- ★ 39,857
- Checked
- Source
- wshobson/agents ↗
- Creator
- wshobson · 179 listings
Similar skills
See all →
SkillDiagnose why a specific ad creative is winning or losingCreative performance analysis
PromptAct as a professional full-stack developer taskedProfessional Full-Stack Developer for Network Mapping & Monitoring Application
SkillEstablishes a project's quality bar as a written contractConstraint driven development
SkillInstruments code so production behavior is visibleObservability and instrumentation
SkillOptimizes application performance across frontend, backendPerformance optimization
SkillDiscovers and invokes agent skillsUsing agent skillsMore from wshobson
SkillMaster C/.NET backend development patterns for building
SkillImplement WCAG 2.2 compliant interfaces with mobileAccessibility compliance
SkillMaster Material Design 3 and Jetpack Compose patternsAndroid Mobile Design
SkillMigrate from AngularJS to Angular using hybrid modeAngular migration
SkillUnderstand anti-reversing, obfuscationAnti reversing techniques
SkillBuild production Apache Airflow DAGs with best practicesApache Airflow DAG Patterns