Sql Optimization
by @codekungfu
Deep SQL performance workflow—symptom framing, execution plans, indexing strategy, query rewrite, locking/transaction behavior, statistics, partitioning, and...
clawhub install sql-optimization📖 About This Skill
name: sql-optimization description: Deep SQL performance workflow—symptom framing, execution plans, indexing strategy, query rewrite, locking/transaction behavior, statistics, partitioning, and verification. Use when queries time out, DB CPU spikes, or migrations change access patterns.
SQL Optimization (Deep Workflow)
Optimization without measurement is guesswork. Structure the work as observe → explain (plan) → change → verify, with explicit attention to correctness, locks, and write amplification from indexes.
When to Offer This Workflow
Trigger conditions:
Initial offer:
Use six stages: (1) frame the problem, (2) reproduce & measure, (3) read execution plans, (4) schema & indexes, (5) query & transaction tuning, (6) verify & guardrail. Confirm engine (PostgreSQL, MySQL, SQL Server, etc.) and environment (prod-like data volume).
Stage 1: Frame the Problem
Goal: Define SLO, scope, and non-goals.
Questions
1. Which queries or endpoints are slow? User-facing vs batch? 2. Regression—did deploy, data volume, or stats change? 3. Isolation level and consistency requirements—can we read replicas? 4. Write risk: is this table write-heavy? Index cost?
Exit condition: One-line problem statement with metric (e.g., “p95 2.4s on /reports at 10k RPS”).
Stage 2: Reproduce & Measure
Goal: Stable repro with representative cardinality and parameters.
Actions
Pitfalls
Exit condition: Baseline numbers + plan hash or saved plan for A/B.
Stage 3: Read Execution Plans
Goal: Name the dominant cost: seq scan, bad join order, sort, hash spill, nested loop explosion.
Interpret (adapt to engine)
FOR UPDATE, long transactions, hot row updatesExit condition: Hypothesis tied to plan node(s), not generic “add index.”
Stage 4: Schema & Indexes
Goal: Right indexes for read paths without destroying writes.
Strategy
ANALYZE, extended stats, histograms—when stale stats lieAdvanced (when relevant)
Exit condition: DDL proposal with rationale and rollback (drop index concurrently if supported).
Stage 5: Query & Transaction Tuning
Goal: Sometimes the fix is SQL rewrite, not hardware.
Techniques
SELECT FOR UPDATEExit condition: New plan shows lower cost / measured latency; lock time acceptable.
Stage 6: Verify & Guardrail
Goal: Improvement holds under load and doesn’t regress neighbors.