SQL Optimization Patterns
Specialist in diagnosing and fixing SQL performance bottlenecks through query plan analysis and indexing strategies.
When to Use This Skill
Use when:
- SQL queries exceed SLA or performance requirements
- Need to diagnose slow queries using EXPLAIN analysis
- Designing database schemas and indexing strategies for analytics workloads
- Reducing database costs through query efficiency
- Optimizing joins, aggregations, or complex analytical queries
- Investigating full table scans and expensive operations
- Implementing index strategies for high-performance reads
- Performance debugging when queries are slow in production
Core Capabilities
- Query Plan Analysis - Read EXPLAIN output to identify bottlenecks
- Indexing Strategies - Design B-tree, hash, GIN, BRIN indexes for query patterns
- Join Optimization - Choose strategies (nested loop, hash, merge) based on data size
- Schema Design - Denormalization, partitioning, materialized views for analytics
- Query Refactoring - Rewrite slow queries using window functions, CTEs, batch operations
- Cost Reduction - Improve query efficiency to reduce compute costs and resource usage
Reference Guides
For detailed implementation guidance, see:
EXPLAIN & Query Plans
Use when: Analyzing slow query performance
Covers:
- Understanding EXPLAIN output across PostgreSQL, MySQL, Snowflake, BigQuery
- Key metrics (Seq Scan, Index Scan, cost, rows, execution time)
- Reading execution plans from bottom-up
- Identifying bottlenecks and cardinality issues
Indexing Strategies
Use when: Designing indexes for analytics workloads
Covers:
- Index types (B-tree, hash, GIN, BRIN, covering, partial)
- Selectivity and composite index design
- Partial and expression indexes
- Avoiding over-indexing and unused indexes
- Index maintenance (ANALYZE, VACUUM, reindex)
Query Optimization Patterns
Use when: Rewriting queries for better performance
Covers:
- Eliminating N+1 query problems
- Cursor-based pagination (vs OFFSET)
- Optimizing COUNT and GROUP BY
- Transforming correlated subqueries
- Using CTEs and window functions
- Batch processing patterns
Advanced Techniques
Use when: Using advanced database features
Covers:
- Materialized views for pre-computation
- Table partitioning for large tables
- Query hints and optimization control
- Performance monitoring and statistics
- Connection pooling and tuning
Quick Decision Guide
| Problem |
Reference |
| Query is slow |
EXPLAIN & Query Plans |
| Need to add indexes |
Indexing Strategies |
| Rewrite query efficiently |
Query Optimization Patterns |
| Advanced optimization |
Advanced Techniques |
Optimization Workflow
Phase 1: Diagnosis
- Capture slow query with
EXPLAIN ANALYZE
- Identify bottleneck: sequential scan, expensive join, high cost estimate
- Understand data volumes and selectivity
Phase 2: Root Cause Analysis
- Check for missing indexes on filter/join columns
- Review join strategy (nested loop vs hash vs merge)
- Analyze cardinality estimates vs actual rows
Phase 3: Optimization
- Add indexes (B-tree, hash, GIN, BRIN as appropriate)
- Rewrite query to reduce complexity (CTEs, window functions)
- Consider denormalization or materialized views
- Measure impact: runtime, cost, resource usage
Phase 4: Validation
- Test optimization with production data volume
- Monitor side effects (index maintenance overhead, storage)
- Document solution and performance improvement
Best Practices
Performance Analysis
- ✅ Establish Baseline: Measure query runtime, cost, resource usage before optimization
- ✅ Use EXPLAIN ANALYZE: Always run with ANALYZE; never guess at performance
- ✅ Understand Costs: Lower query cost estimate usually correlates with faster execution
- ✅ Check Selectivity: Filters with poor selectivity waste I/O; indexes on selective columns help most
Indexing Strategy
- ✅ Index Selective Columns: Indexes help when filtering/joining on high-cardinality columns
- ✅ Avoid Over-Indexing: Every index slows writes; add only indexes that measurably help
- ✅ Composite Indexes: Order by selectivity (most selective first) and join key order
- ✅ Partial Indexes: Index only relevant subset (e.g., WHERE active = true)
Query Optimization
- ✅ Filter Early: Push WHERE clauses down before joins
- ✅ Minimize Shuffles: Avoid sorting/aggregating large result sets; use indexes for ordering
- ✅ Use Window Functions: More efficient than self-joins for ranking, running totals
- ✅ Denormalize Strategically: Trade write complexity for read speed when appropriate
Common Pitfalls
| Pitfall |
Root Cause |
Fix |
| Missing index |
Obvious filter on non-indexed column |
Add index on frequently filtered columns |
| Unused index |
Index added but never used |
Use EXPLAIN; verify index is selected by planner |
| Indexing without EXPLAIN |
Adding indexes blindly |
Run EXPLAIN ANALYZE before/after; confirm improvement |
| Bad join order |
Joining large table first |
Filter before joins; use EXPLAIN to understand order |
| Over-indexing |
Every column indexed |
Remove unused indexes; focus on high-value queries |
| Stale statistics |
Query plan based on old stats |
Run VACUUM ANALYZE regularly |
Dependencies
- senior-data-engineer - For schema design and performance mentorship
1---2name: sql-optimization-patterns3description: Specialist in SQL query optimization—index strategies, EXPLAIN analysis, query tuning. Transforms slow queries into fast ones through systematic diagnosis and targeted optimization.4---56# SQL Optimization Patterns78Specialist in diagnosing and fixing SQL performance bottlenecks through query plan analysis and indexing strategies.910## When to Use This Skill1112Use when:1314- SQL queries exceed SLA or performance requirements15- Need to diagnose slow queries using EXPLAIN analysis16- Designing database schemas and indexing strategies for analytics workloads17- Reducing database costs through query efficiency18- Optimizing joins, aggregations, or complex analytical queries19- Investigating full table scans and expensive operations20- Implementing index strategies for high-performance reads21- Performance debugging when queries are slow in production2223---2425## Core Capabilities26271. **Query Plan Analysis** - Read EXPLAIN output to identify bottlenecks282. **Indexing Strategies** - Design B-tree, hash, GIN, BRIN indexes for query patterns293. **Join Optimization** - Choose strategies (nested loop, hash, merge) based on data size304. **Schema Design** - Denormalization, partitioning, materialized views for analytics315. **Query Refactoring** - Rewrite slow queries using window functions, CTEs, batch operations326. **Cost Reduction** - Improve query efficiency to reduce compute costs and resource usage3334---3536## Reference Guides3738For detailed implementation guidance, see:3940### [EXPLAIN & Query Plans](references/explain-query-plans.md)4142**Use when:** Analyzing slow query performance4344Covers:4546- Understanding EXPLAIN output across PostgreSQL, MySQL, Snowflake, BigQuery47- Key metrics (Seq Scan, Index Scan, cost, rows, execution time)48- Reading execution plans from bottom-up49- Identifying bottlenecks and cardinality issues5051### [Indexing Strategies](references/indexing-strategies.md)5253**Use when:** Designing indexes for analytics workloads5455Covers:5657- Index types (B-tree, hash, GIN, BRIN, covering, partial)58- Selectivity and composite index design59- Partial and expression indexes60- Avoiding over-indexing and unused indexes61- Index maintenance (ANALYZE, VACUUM, reindex)6263### [Query Optimization Patterns](references/query-optimization.md)6465**Use when:** Rewriting queries for better performance6667Covers:6869- Eliminating N+1 query problems70- Cursor-based pagination (vs OFFSET)71- Optimizing COUNT and GROUP BY72- Transforming correlated subqueries73- Using CTEs and window functions74- Batch processing patterns7576### [Advanced Techniques](references/advanced-techniques.md)7778**Use when:** Using advanced database features7980Covers:8182- Materialized views for pre-computation83- Table partitioning for large tables84- Query hints and optimization control85- Performance monitoring and statistics86- Connection pooling and tuning8788---8990## Quick Decision Guide9192| Problem | Reference |93| :------ | :-------- |94| Query is slow | [EXPLAIN & Query Plans](references/explain-query-plans.md) |95| Need to add indexes | [Indexing Strategies](references/indexing-strategies.md) |96| Rewrite query efficiently | [Query Optimization Patterns](references/query-optimization.md) |97| Advanced optimization | [Advanced Techniques](references/advanced-techniques.md) |9899---100101## Optimization Workflow102103### Phase 1: Diagnosis1041051. Capture slow query with `EXPLAIN ANALYZE`1062. Identify bottleneck: sequential scan, expensive join, high cost estimate1073. Understand data volumes and selectivity108109### Phase 2: Root Cause Analysis1101111. Check for missing indexes on filter/join columns1122. Review join strategy (nested loop vs hash vs merge)1133. Analyze cardinality estimates vs actual rows114115### Phase 3: Optimization1161171. Add indexes (B-tree, hash, GIN, BRIN as appropriate)1182. Rewrite query to reduce complexity (CTEs, window functions)1193. Consider denormalization or materialized views1204. Measure impact: runtime, cost, resource usage121122### Phase 4: Validation1231241. Test optimization with production data volume1252. Monitor side effects (index maintenance overhead, storage)1263. Document solution and performance improvement127128---129130## Best Practices131132### Performance Analysis133134- ✅ **Establish Baseline**: Measure query runtime, cost, resource usage before optimization135- ✅ **Use EXPLAIN ANALYZE**: Always run with ANALYZE; never guess at performance136- ✅ **Understand Costs**: Lower query cost estimate usually correlates with faster execution137- ✅ **Check Selectivity**: Filters with poor selectivity waste I/O; indexes on selective columns help most138139### Indexing Strategy140141- ✅ **Index Selective Columns**: Indexes help when filtering/joining on high-cardinality columns142- ✅ **Avoid Over-Indexing**: Every index slows writes; add only indexes that measurably help143- ✅ **Composite Indexes**: Order by selectivity (most selective first) and join key order144- ✅ **Partial Indexes**: Index only relevant subset (e.g., WHERE active = true)145146### Query Optimization147148- ✅ **Filter Early**: Push WHERE clauses down before joins149- ✅ **Minimize Shuffles**: Avoid sorting/aggregating large result sets; use indexes for ordering150- ✅ **Use Window Functions**: More efficient than self-joins for ranking, running totals151- ✅ **Denormalize Strategically**: Trade write complexity for read speed when appropriate152153---154155## Common Pitfalls156157| Pitfall | Root Cause | Fix |158| :------ | :--------- | :-- |159| Missing index | Obvious filter on non-indexed column | Add index on frequently filtered columns |160| Unused index | Index added but never used | Use EXPLAIN; verify index is selected by planner |161| Indexing without EXPLAIN | Adding indexes blindly | Run EXPLAIN ANALYZE before/after; confirm improvement |162| Bad join order | Joining large table first | Filter before joins; use EXPLAIN to understand order |163| Over-indexing | Every column indexed | Remove unused indexes; focus on high-value queries |164| Stale statistics | Query plan based on old stats | Run VACUUM ANALYZE regularly |165166---167168## Dependencies169170- **senior-data-engineer** - For schema design and performance mentorship