cosmix/loom/loom-sql-optimization
Claude Code and agent skill by cosmix/loom
- community
- ext:[{"type":"hook","description":"Pre/post lifecycle hooks"}]
Checking that the SKILL.md file is still in the repository.
Analyzes and optimizes SQL queries for performance.
Install
npx vskill@latest install cosmix/loom/loom-sql-optimizationSemi-extensibleMentions customization, but needs skill-specific knowledge. Read the extensible skills standard
SKILL.md
The same SKILL.md was published earlier as cosmix/loom/loom-sql-optimization.
SQL Optimization
Overview
Analyzing and tuning SQL for performance: reading execution plans, index design, query rewriting, and PostgreSQL-specific behavior. Most notes assume PostgreSQL. The mechanism-level material — reading EXPLAIN, composite-index column order, partial-index limits, statistics, concurrency — is in Expert Practices below; this section is the workflow and the anti-pattern catalogue.
Workflow
- Find the slow query (logs,
pg_stat_statementsby total time, not just per-call). - Explain it:
EXPLAIN (ANALYZE, BUFFERS, SETTINGS). Read plans by estimated-vs-actual row divergence (bad stats → wrong join/scan choice), scan type, join algorithm, andRows Removed by Filter. See Expert Practices → Reading EXPLAIN. - Fix in priority order: refresh/extend statistics → add/reshape an index → rewrite the query → denormalize/derive → tune config. Change one thing at a time.
- Validate: re-EXPLAIN on production-like data, confirm the target node changed (Sort gone / Index Scan chosen / Heap Fetches low), verify correctness, monitor post-deploy.
Best Practices
- `EXPLAIN (ANALYZE, BUFFERS)` is the source of truth — never optimize by guessing; actual rows and buffers reveal the real cost.
- Select only needed columns (enables index-only scans; avoids TOAST/wide-row I/O).
- Index for WHERE/JOIN/ORDER BY, but mind column order and the write tax (Expert Practices → Index Design).
- Avoid N+1: one JOIN or a batched
WHERE id = ANY($1), not a query per row. - `NOT EXISTS`, never `NOT IN (nullable subquery)` — one NULL silently returns zero rows;
NOT EXISTSis NULL-safe and hash-anti-join-able. (InclusionIN/ANY/EXISTSplan identically in modern PG — pick readability.) - No functions/implicit casts on indexed columns (
WHERE lower(x)=needs an expression index;WHERE int_col = '1'may cast and skip the index). - Keyset pagination, not deep
OFFSET(Expert Practices). - CTEs are not fences (PG12+): a non-recursive, side-effect-free CTE used once is inlined; used >1× it materializes. Force with
AS MATERIALIZED/AS NOT MATERIALIZED; theOFFSET 0trick is obsolete. - `ANALYZE` after bulk loads; monitor query performance over time.
PostgreSQL-Specific Optimizations
Execution Plan Operators
Scan Types:
- Sequential Scan: Full table scan (slow for large tables)
- Index Scan: Walks the index then fetches matching heap rows — best when the predicate matches only a SMALL fraction of the table. When many rows match, the planner switches to a Sequential Scan (or Bitmap Heap Scan for a middling fraction) because the random heap I/O of many index lookups costs more than reading the table sequentially.
- Index Only Scan: Uses covering index (fastest)
- Bitmap Index Scan: Multiple index scans combined (good for OR conditions)
Join Algorithms:
- Nested Loop: Best for small tables or index lookups
- Hash Join: Best for medium-sized tables with equality joins
- Merge Join: Best for large pre-sorted tables
Statistics and Maintenance
Configuration Tuning
work_mem is the limit for each sort/hash operation and each parallel worker — a single query with several such nodes can use N × work_mem simultaneously, and concurrent sessions multiply that further. Since PG14, hash operations use up to hash_mem_multiplier × work_mem (default 2.0). A large global work_mem on a high-concurrency server is an OOM risk: keep the global value modest and raise it per-session with SET LOCAL work_mem for known heavy reports. Set log_temp_files = 0 and watch for Batches > 1 on Hash nodes in EXPLAIN ANALYZE to detect spills.
Common Anti-Patterns
1. SELECT \* in Application Code
2. Implicit Type Conversion
3. OR Conditions Without Indexes
PostgreSQL generally rewrites OR conditions on the SAME column into IN/ANY and can use a plain B-tree index on that column directly. For OR conditions across DIFFERENT columns it combines separate index scans via a BitmapOr (or you can rewrite as UNION ALL). Verify the chosen path with EXPLAIN rather than assuming a partial index helps — a partial index only restricts which rows are indexed; it does not provide an access path for searching by those status values.
4. Correlated Subqueries
5. Missing WHERE Clauses
Advanced Patterns
CTEs (Common Table Expressions)
Window Functions
Examples
Example 1: Query Optimization with EXPLAIN
Example 2: N+1 Query Problem
Example 3: Index Design Strategies
Example 4: Query Rewriting Patterns
This is the start of the file. Read the full SKILL.md on GitHub.
Security
- Security scanPassed, 95 of 100Pattern checks on the skill's files.
- Model reviewPassed
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingskills/loom-sql-optimization/SKILL.md
Popularity
- Repository stars
- 56
- Repository forks
- 3
- 7-day trend score
- 20
Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.
Extension points
hookPre/post lifecycle hooks
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/cosmix/loom/loom-sql-optimization)