Sql optimization patterns

From kumaran-is/claude-code-onboarding · View interactive version

Sql optimization patterns is an AI agent skill from the GitHub repository kumaran-is/claude-code-onboarding. Transforms slow PostgreSQL queries into fast operations through systematic EXPLAIN ANALYZE, indexing strategies, N+1 elimination, cursor pagination, and materialized views. Use when diagnosing slow queries, optimizing database performance, or designing index strategies — always profile before optimi

How to use this skill

Skill file

Iron Law

PROFILE BEFORE OPTIMIZING — RUN EXPLAIN (ANALYZE, BUFFERS) ON THE ACTUAL SLOW QUERY BEFORE WRITING A SINGLE INDEX

When to Use This Skill

Do Not Use This Skill When

Quick Reference

| Problem | Diagnosis | Fix |

|---------|-----------|-----|

| Slow endpoint | EXPLAIN (ANALYZE, BUFFERS) — look for Seq Scan | Add index on WHERE/JOIN columns |

| N+1 queries | Count DB calls per request > 1 | JOIN + eager load or batch query |

| Slow pagination | OFFSET on large table | Cursor-based pagination |

| Slow aggregation | GROUP BY without index | Partial index + filter before GROUP BY |

| Slow COUNT(*) | Full table count | pg_class.reltuples estimate or index-only count |

| Repeated expensive query | Same query hits DB repeatedly | Materialized view + scheduled refresh |

| Large table slow scans | Millions of rows, date filter | Table partitioning by date range |

Process

Step 1 — Identify the Slow Query

-- Find the top-10 slowest queries by mean execution time
SELECT query, calls, total_exec_time, mean_exec_time
FROM pg_stat_statements
ORDER BY mean_exec_time DESC
LIMIT 10;

Step 2 — Profile with EXPLAIN

-- Always use ANALYZE + BUFFERS for real data
EXPLAIN (ANALYZE, BUFFERS, VERBOSE)
SELECT u.id, u.email, COUNT(o.id) AS order_count
FROM users u
JOIN orders o ON u.id = o.user_id
WHERE u.created_at > NOW() - INTERVAL '30 days'
GROUP BY u.id, u.email;

Key nodes to watch:

Step 3 — Apply the Right Fix

See resources/implementation-playbook.md for SQL code for each pattern.

Step 4 — Verify Improvement

-- Re-run EXPLAIN ANALYZE after index/change
-- Compare: Execution Time before vs after
-- Compare: Seq Scan → Index Only Scan

Optimization Patterns (Summary)

Load resources/implementation-playbook.md for full SQL code examples.

| Pattern | When | Speedup |

|---------|------|---------|

| Composite index | Multi-column WHERE/ORDER BY | 10x–100x |

| Partial index | Filtered subset (e.g., active users) | 5x–50x |

| Covering index | Avoid table heap access | 2x–10x |

| Cursor pagination | Replace OFFSET 100000 | 100x+ |

| N+1 elimination | ORM loop → single JOIN | N× → 1 query |

| Materialized view | Repeated expensive aggregation | 100x+ |

| Batch operations | Individual inserts/updates in loop | 10x–50x |

| Table partitioning | Time-series or date-range tables >10M rows | 5x–20x |

Stack Integration

Python / FastAPI (asyncpg + SQLAlchemy)

NestJS / Prisma

Java / Spring Boot WebFlux (R2DBC)

Anti-Patterns

Documentation Sources

Reference Files

Related Skills

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.