[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M79AK978238C8V97PJ9WW4RT":3,"skill-same:01M79AK978238C8V97PJ9WW4RT":123},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":59,"commitSha":60,"skillDirectory":61,"forksCount":14,"repositoryHtmlUrl":62,"repositoryHomepageUrl":6,"ownerHtmlUrl":63,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":64,"install":65,"resources":78},"01M79AK978238C8V97PJ9WW4RT","sql-query-optimization",null,"SQL query optimization for PostgreSQL\u002FMySQL with indexing, EXPLAIN analysis. Use for slow queries, N+1 problems, missing indexes, or encountering sequential scans, OFFSET pagination, temp table spills, inefficient JOINs.","Elogic360\u002Fsoftware-factory","Elogic360","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F156535519?v=4","01M74NH3F0RB13PWB7JZDE2V80","elogic360","01M74NH3FPC65082MDZVMFHDM3",0,"MIT","https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fintegrations\u002Fclaude-skills-secondsky\u002Fplugins\u002Fsql-query-optimization\u002Fskills\u002Fsql-query-optimization\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: sql-query-optimization\ndescription: \"SQL query optimization for PostgreSQL\u002FMySQL with indexing, EXPLAIN analysis. Use for slow queries, N+1 problems, missing indexes, or encountering sequential scans, OFFSET pagination, temp table spills, inefficient JOINs.\"\n\nmetadata:\n  keywords:\n    - sql optimization\n    - query performance\n    - database indexes\n    - explain analyze\n    - slow queries\n    - n+1 problem\n    - query plan\n    - index strategy\n    - composite index\n    - covering index\n    - postgresql performance\n    - mysql optimization\n    - query rewriting\n    - prepared statements\n    - connection pooling\n    - sequential scan\n    - missing index\n    - SELECT *\n    - LIMIT optimization\n    - subquery performance\n    - pagination\n    - cursor based pagination\n    - batch operations\n    - pg_stat_statements\n    - full-text search\n    - bitmap scan\n    - index only scan\n    - query tuning\n    - database performance\n    - cache hit ratio\n    - work_mem\n    - shared_buffers\n    - database monitoring\n\nlicense: MIT\n---\n# SQL Query Optimization\n\n**Status**: Production Ready ✅\n**Last Updated**: 2025-12-15\n**Latest Versions**: PostgreSQL 17, MySQL 8.4\n**Dependencies**: None\n\n---\n\n## Quick Start (10 Minutes)\n\n### 1. Identify Slow Query\n\n```sql\n-- PostgreSQL: Enable pg_stat_statements\nCREATE EXTENSION IF NOT EXISTS pg_stat_statements;\n\n-- Find slowest queries\nSELECT query, mean_exec_time, calls\nFROM pg_stat_statements\nORDER BY mean_exec_time DESC\nLIMIT 10;\n```\n\n### 2. Analyze with EXPLAIN\n\n```sql\nEXPLAIN (ANALYZE, BUFFERS, VERBOSE)\nSELECT * FROM orders WHERE user_id = 123;\n\n-- Look for:\n-- - Seq Scan on large tables → needs index\n-- - High \"Rows Removed by Filter\" → poor selectivity\n-- - Temp read\u002Fwritten → increase work_mem\n```\n\n### 3. Create Index\n\n```sql\n-- Add missing index\nCREATE INDEX CONCURRENTLY idx_orders_user\nON orders(user_id);\n\n-- Verify improvement\nEXPLAIN (ANALYZE, BUFFERS)\nSELECT * FROM orders WHERE user_id = 123;\n-- Execution time should drop 10-100x\n```\n\n---\n\n## Critical Rules\n\n### Always Do ✓\n\n| Rule | Why | Example |\n|------|-----|---------|\n| Index foreign keys | JOINs need indexed columns | `CREATE INDEX idx_orders_user ON orders(user_id)` |\n| Use EXPLAIN ANALYZE before production | Verify query plan is optimal | `EXPLAIN (ANALYZE, BUFFERS) \u003Cquery>` |\n| Select specific columns | Reduces data transfer 90% | `SELECT id, name FROM users` not `SELECT *` |\n| Add LIMIT to unbounded queries | Prevents memory exhaustion | `SELECT * FROM logs ORDER BY id LIMIT 100` |\n| Use prepared statements | Prevents SQL injection + faster | `db.query('SELECT * FROM users WHERE id = $1', [id])` |\n| Run ANALYZE after bulk operations | Updates query planner statistics | `ANALYZE table_name` |\n| Monitor pg_stat_statements | Track query performance over time | Review daily for regressions |\n| Use connection pooling | Reduces connection overhead 10x | `new Pool({ max: 20 })` |\n\n### Never Do ✗\n\n| Anti-Pattern | Problem | Fix |\n|--------------|---------|-----|\n| SELECT * in production | Fetches unnecessary columns | Select specific columns only |\n| Leading wildcard LIKE '%term%' | Cannot use index | Use full-text search instead |\n| String concatenation for SQL | SQL injection vulnerability | Use parameterized queries |\n| No LIMIT on large results | Memory exhaustion | Always add LIMIT + pagination |\n| N+1 queries in loops | Network latency × N | Use JOIN or batch loading |\n| Ignoring EXPLAIN output | Deploy slow queries to production | Always EXPLAIN before deploy |\n| Multiple INSERTs in loop | Slow bulk operations | Use batch INSERT with multiple VALUES |\n| OFFSET for pagination | O(n) time, scans skipped rows | Use cursor-based pagination |\n\n---\n\n## Top 7 Critical Errors\n\n### 1. Sequential Scan on Large Table\n**Symptom**: `Seq Scan on orders (cost=0.00..150000.00)` on 1M+ rows\n**Cause**: No index on filter column\n**Fix**: `CREATE INDEX idx_orders_column ON orders(column)`\n**Impact**: 10-100x faster\n\n### 2. Missing Index on Foreign Key\n**Symptom**: Slow JOINs (5+ seconds)\n**Cause**: Foreign key columns not indexed\n**Fix**: `CREATE INDEX idx_orders_user_id ON orders(user_id)`\n**Impact**: 50-500x faster JOINs\n\n### 3. N+1 Query Problem\n**Symptom**: 1 + N queries for N records\n**Cause**: ORM lazy loading in loop\n**Fix**: Use JOIN or eager loading: `SELECT u.*, o.* FROM users u LEFT JOIN orders o ON u.id = o.user_id`\n**Impact**: N queries → 1 query\n\n### 4. Leading Wildcard LIKE\n**Symptom**: `WHERE name LIKE '%search%'` sequential scan\n**Cause**: Index cannot match middle of string\n**Fix**: Use full-text search (GIN index) or trigrams\n**Impact**: 100-1000x faster\n\n### 5. SELECT * in Production\n**Symptom**: High network traffic, slow responses\n**Cause**: Fetches all 50 columns instead of needed 3\n**Fix**: `SELECT id, name, email` (explicit column list)\n**Impact**: 90% less data transfer\n\n### 6. Missing LIMIT on Large Results\n**Symptom**: Server out of memory, query timeout\n**Cause**: Attempting to return 5M rows\n**Fix**: `SELECT * FROM logs WHERE ... LIMIT 100` + pagination\n**Impact**: Constant memory usage\n\n### 7. Stale Statistics After Bulk Load\n**Symptom**: Wrong query plan chosen despite index\n**Cause**: PostgreSQL statistics outdated\n**Fix**: `ANALYZE table_name` after bulk operations\n**Impact**: Correct query plan selection\n\n**See `references\u002Ferror-catalog.md` for all 12 errors with detailed solutions.**\n\n---\n\n## Common Patterns Summary\n\n| Pattern | Use Case | Example | Performance |\n|---------|----------|---------|-------------|\n| **B-Tree Index** | Equality, range, sort queries | `CREATE INDEX idx ON t(col)` | Default, best general purpose |\n| **Composite Index** | Multi-column WHERE clauses | `CREATE INDEX idx ON t(c1, c2)` | 5-50x faster than single index |\n| **Covering Index** | Include all query columns | `CREATE INDEX idx ON t(c1) INCLUDE (c2)` | 2-10x faster (no heap fetch) |\n| **Partial Index** | Filter subset of rows | `CREATE INDEX idx ON t(c) WHERE status='active'` | 50-90% smaller index |\n| **JOIN Rewrite** | Replace IN subquery | `INNER JOIN users u ON o.user_id = u.id` | 5-20x faster than subquery |\n| **Batch INSERT** | Bulk data loading | `INSERT INTO t VALUES (..),(..)` | 10-100x faster than individual |\n| **Cursor Pagination** | Large offset performance | `WHERE id > last_id LIMIT 100` | Constant time vs O(n) |\n\n---\n\n## Configuration Summary\n\n### PostgreSQL Config\n\n```sql\n-- Increase work_mem for complex queries (reloadable - no restart needed)\nSET work_mem = '256MB';\n\n-- Increase shared_buffers for better caching (25% of RAM)\nALTER SYSTEM SET shared_buffers = '8GB';\n\n-- IMPORTANT: shared_buffers requires a full PostgreSQL server restart!\n-- This setting is NOT reloadable via pg_reload_conf()\n--\n-- To apply shared_buffers change:\n-- 1. Stop PostgreSQL:   sudo systemctl stop postgresql\n-- 2. Start PostgreSQL:  sudo systemctl start postgresql\n-- OR use:              sudo systemctl restart postgresql\n--\n-- Verify the change took effect:\n-- SHOW shared_buffers;\n\n-- Enable auto-vacuum (reloadable - can use pg_reload_conf)\nALTER SYSTEM SET autovacuum = on;\n\n-- Reload config (ONLY works for parameters that don't require restart)\n-- This will NOT reload shared_buffers - restart required for that!\nSELECT pg_reload_conf();\n```\n\n### MySQL Config\n\n```ini\n# my.cnf\n[mysqld]\ninnodb_buffer_pool_size = 8G  # 70% of RAM\nmax_connections = 500\nslow_query_log = 1\nlong_query_time = 1\n```\n\n---\n\n## When to Load References\n\n**Performance Analysis**:\n- Load `references\u002Fexplain-analysis.md` when: Reading EXPLAIN output, understanding query plans, analyzing buffer statistics, comparing PostgreSQL vs MySQL EXPLAIN\n- Load `references\u002Fperformance-monitoring.md` when: Setting up monitoring, tracking slow queries over time, monitoring cache hit ratios, identifying bloated tables\n\n**Index Optimization**:\n- Load `references\u002Findex-strategies.md` when: Choosing index type (B-Tree, GIN, GiST, Hash), creating composite indexes, determining column order, using covering indexes, implementing partial indexes, monitoring index usage\n\n**Query Optimization**:\n- Load `references\u002Fquery-rewrites.md` when: Rewriting slow queries, converting subqueries to JOINs, eliminating N+1 queries, implementing pagination, optimizing LIKE queries, batching operations\n\n**Systematic Process**:\n- Load `references\u002Foptimization-workflow.md` when: Following step-by-step optimization process, creating optimization hypothesis, measuring improvements, monitoring long-term performance\n\n**Error Resolution**:\n- Load `references\u002Ferror-catalog.md` when: Debugging specific errors (sequential scans, missing indexes, N+1 queries, etc.), understanding root causes, implementing verified solutions\n\n---\n\n## Using Bundled Resources\n\n### Templates (Copy-Paste SQL)\n\n```bash\n# EXPLAIN query templates\ntemplates\u002Fexplain-query.sql\n\n# Index creation patterns\ntemplates\u002Findex-examples.sql\n\n# Query rewrite examples\ntemplates\u002Fquery-rewrites.sql\n\n# Monitoring queries\ntemplates\u002Fmonitoring-queries.sql\n```\n\n### References (Deep Dives)\n\n```bash\n# Comprehensive guides\nreferences\u002Ferror-catalog.md              # All 12 errors + solutions\nreferences\u002Fexplain-analysis.md           # Reading query plans\nreferences\u002Findex-strategies.md           # Index types & selection\nreferences\u002Fquery-rewrites.md             # Before\u002Fafter optimizations\nreferences\u002Fperformance-monitoring.md     # Long-term monitoring\nreferences\u002Foptimization-workflow.md      # Systematic process\n```\n\n---\n\n## Dependencies\n\n**PostgreSQL Extensions**:\n- `pg_stat_statements` - Query performance tracking (built-in)\n- `pg_trgm` - Trigram similarity search (optional, for fuzzy matching)\n\n**MySQL**:\n- `performance_schema` - Performance monitoring (enabled by default in 8.0+)\n\n**No additional dependencies required.**\n\n---\n\n## Known Issues Prevention\n\n| Issue | Symptom | Prevention |\n|-------|---------|------------|\n| Sequential scans | Seq Scan on 1M+ rows | Index filter columns before production |\n| Missing FK indexes | Slow JOINs | Always index foreign keys |\n| N+1 queries | 1+N database calls | Use JOIN or eager loading |\n| Leading wildcards | LIKE '%x%' slow | Use full-text search (GIN) |\n| SELECT * bloat | High network traffic | Select specific columns |\n| No LIMIT | Memory exhaustion | Always LIMIT unbounded queries |\n| Stale statistics | Wrong query plans | ANALYZE after bulk operations |\n| Wrong index order | Index exists but not used | Match query pattern |\n| Missing composite | Multiple WHERE slow | Create composite index |\n| No connection pool | High latency | Implement pooling (20-50 connections) |\n| SQL injection | Security vulnerability | Use prepared statements only |\n| Temp spills | Disk I\u002FO on sorts | Increase work_mem |\n\n---\n\n## Complete Setup Checklist\n\nProduction Deployment:\n- [ ] Enable pg_stat_statements or performance_schema\n- [ ] Index all foreign key columns\n- [ ] Index columns in WHERE, JOIN, ORDER BY clauses\n- [ ] Replace SELECT * with specific columns\n- [ ] Add LIMIT to all unbounded queries\n- [ ] Use prepared statements (parameterized queries)\n- [ ] Implement connection pooling (20-50 connections)\n- [ ] Configure work_mem (256MB-1GB per connection)\n- [ ] Configure shared_buffers (25% of RAM for PostgreSQL)\n- [ ] Enable slow query logging (threshold: 100-1000ms)\n- [ ] Run EXPLAIN ANALYZE on all critical queries\n- [ ] Set up daily monitoring of pg_stat_statements\n- [ ] Schedule ANALYZE after nightly bulk operations\n- [ ] Monitor cache hit ratio (target: >99%)\n- [ ] Review and drop unused indexes monthly\n\n---\n\n## Production Example\n\n**Before Optimization**:\n```sql\n-- Query: Fetch user orders\nSELECT * FROM orders WHERE user_id = 123;\n\n-- Performance:\n-- Execution time: 2500ms\n-- Seq Scan on orders (1M rows scanned)\n-- Network: 50MB transferred\n-- No index on user_id\n```\n\n**After Optimization**:\n```sql\n-- Add index\nCREATE INDEX CONCURRENTLY idx_orders_user_id ON orders(user_id);\n\n-- Optimize query\nSELECT id, total, status, created_at\nFROM orders\nWHERE user_id = 123\nLIMIT 100;\n\n-- Performance:\n-- Execution time: 12ms (208x faster!)\n-- Index Scan using idx_orders_user_id (100 rows)\n-- Network: 50KB transferred (1000x less!)\n-- Covering index with INCLUDE\n```\n\n**Result**: 208x faster execution, 1000x less data transfer\n\n---\n\n**For comprehensive optimization guidance, error resolution, and production patterns, load the appropriate reference files listed in \"When to Load References\" above.**\n","# SQL Query Optimization\n\n**Status**: Production Ready ✅\n**Last Updated**: 2025-12-15\n**Latest Versions**: PostgreSQL 17, MySQL 8.4\n**Dependencies**: None\n\n---\n\n## Quick Start (10 Minutes)\n\n### 1. Identify Slow Query\n\n```sql\n-- PostgreSQL: Enable pg_stat_statements\nCREATE EXTENSION IF NOT EXISTS pg_stat_statements;\n\n-- Find slowest queries\nSELECT query, mean_exec_time, calls\nFROM pg_stat_statements\nORDER BY mean_exec_time DESC\nLIMIT 10;\n```\n\n### 2. Analyze with EXPLAIN\n\n```sql\nEXPLAIN (ANALYZE, BUFFERS, VERBOSE)\nSELECT * FROM orders WHERE user_id = 123;\n\n-- Look for:\n-- - Seq Scan on large tables → needs index\n-- - High \"Rows Removed by Filter\" → poor selectivity\n-- - Temp read\u002Fwritten → increase work_mem\n```\n\n### 3. Create Index\n\n```sql\n-- Add missing index\nCREATE INDEX CONCURRENTLY idx_orders_user\nON orders(user_id);\n\n-- Verify improvement\nEXPLAIN (ANALYZE, BUFFERS)\nSELECT * FROM orders WHERE user_id = 123;\n-- Execution time should drop 10-100x\n```\n\n---\n\n## Critical Rules\n\n### Always Do ✓\n\n| Rule | Why | Example |\n|------|-----|---------|\n| Index foreign keys | JOINs need indexed columns | `CREATE INDEX idx_orders_user ON orders(user_id)` |\n| Use EXPLAIN ANALYZE before production | Verify query plan is optimal | `EXPLAIN (ANALYZE, BUFFERS) \u003Cquery>` |\n| Select specific columns | Reduces data transfer 90% | `SELECT id, name FROM users` not `SELECT *` |\n| Add LIMIT to unbounded queries | Prevents memory exhaustion | `SELECT * FROM logs ORDER BY id LIMIT 100` |\n| Use prepared statements | Prevents SQL injection + faster | `db.query('SELECT * FROM users WHERE id = $1', [id])` |\n| Run ANALYZE after bulk operations | Updates query planner statistics | `ANALYZE table_name` |\n| Monitor pg_stat_statements | Track query performance over time | Review daily for regressions |\n| Use connection pooling | Reduces connection overhead 10x | `new Pool({ max: 20 })` |\n\n### Never Do ✗\n\n| Anti-Pattern | Problem | Fix |\n|--------------|---------|-----|\n| SELECT * in production | Fetches unnecessary columns | Select specific columns only |\n| Leading wildcard LIKE '%term%' | Cannot use index | Use full-text search instead |\n| String concatenation for SQL | SQL injection vulnerability | Use parameterized queries |\n| No LIMIT on large results | Memory exhaustion | Always add LIMIT + pagination |\n| N+1 queries in loops | Network latency × N | Use JOIN or batch loading |\n| Ignoring EXPLAIN output | Deploy slow queries to production | Always EXPLAIN before deploy |\n| Multiple INSERTs in loop | Slow bulk operations | Use batch INSERT with multiple VALUES |\n| OFFSET for pagination | O(n) time, scans skipped rows | Use cursor-based pagination |\n\n---\n\n## Top 7 Critical Errors\n\n### 1. Sequential Scan on Large Table\n**Symptom**: `Seq Scan on orders (cost=0.00..150000.00)` on 1M+ rows\n**Cause**: No index on filter column\n**Fix**: `CREATE INDEX idx_orders_column ON orders(column)`\n**Impact**: 10-100x faster\n\n### 2. Missing Index on Foreign Key\n**Symptom**: Slow JOINs (5+ seconds)\n**Cause**: Foreign key columns not indexed\n**Fix**: `CREATE INDEX idx_orders_user_id ON orders(user_id)`\n**Impact**: 50-500x faster JOINs\n\n### 3. N+1 Query Problem\n**Symptom**: 1 + N queries for N records\n**Cause**: ORM lazy loading in loop\n**Fix**: Use JOIN or eager loading: `SELECT u.*, o.* FROM users u LEFT JOIN orders o ON u.id = o.user_id`\n**Impact**: N queries → 1 query\n\n### 4. Leading Wildcard LIKE\n**Symptom**: `WHERE name LIKE '%search%'` sequential scan\n**Cause**: Index cannot match middle of string\n**Fix**: Use full-text search (GIN index) or trigrams\n**Impact**: 100-1000x faster\n\n### 5. SELECT * in Production\n**Symptom**: High network traffic, slow responses\n**Cause**: Fetches all 50 columns instead of needed 3\n**Fix**: `SELECT id, name, email` (explicit column list)\n**Impact**: 90% less data transfer\n\n### 6. Missing LIMIT on Large Results\n**Symptom**: Server out of memory, query timeout\n**Cause**: Attempting to return 5M rows\n**Fix**: `SELECT * FROM logs WHERE ... LIMIT 100` + pagination\n**Impact**: Constant memory usage\n\n### 7. Stale Statistics After Bulk Load\n**Symptom**: Wrong query plan chosen despite index\n**Cause**: PostgreSQL statistics outdated\n**Fix**: `ANALYZE table_name` after bulk operations\n**Impact**: Correct query plan selection\n\n**See `references\u002Ferror-catalog.md` for all 12 errors with detailed solutions.**\n\n---\n\n## Common Patterns Summary\n\n| Pattern | Use Case | Example | Performance |\n|---------|----------|---------|-------------|\n| **B-Tree Index** | Equality, range, sort queries | `CREATE INDEX idx ON t(col)` | Default, best general purpose |\n| **Composite Index** | Multi-column WHERE clauses | `CREATE INDEX idx ON t(c1, c2)` | 5-50x faster than single index |\n| **Covering Index** | Include all query columns | `CREATE INDEX idx ON t(c1) INCLUDE (c2)` | 2-10x faster (no heap fetch) |\n| **Partial Index** | Filter subset of rows | `CREATE INDEX idx ON t(c) WHERE status='active'` | 50-90% smaller index |\n| **JOIN Rewrite** | Replace IN subquery | `INNER JOIN users u ON o.user_id = u.id` | 5-20x faster than subquery |\n| **Batch INSERT** | Bulk data loading | `INSERT INTO t VALUES (..),(..)` | 10-100x faster than individual |\n| **Cursor Pagination** | Large offset performance | `WHERE id > last_id LIMIT 100` | Constant time vs O(n) |\n\n---\n\n## Configuration Summary\n\n### PostgreSQL Config\n\n```sql\n-- Increase work_mem for complex queries (reloadable - no restart needed)\nSET work_mem = '256MB';\n\n-- Increase shared_buffers for better caching (25% of RAM)\nALTER SYSTEM SET shared_buffers = '8GB';\n\n-- IMPORTANT: shared_buffers requires a full PostgreSQL server restart!\n-- This setting is NOT reloadable via pg_reload_conf()\n--\n-- To apply shared_buffers change:\n-- 1. Stop PostgreSQL:   sudo systemctl stop postgresql\n-- 2. Start PostgreSQL:  sudo systemctl start postgresql\n-- OR use:              sudo systemctl restart postgresql\n--\n-- Verify the change took effect:\n-- SHOW shared_buffers;\n\n-- Enable auto-vacuum (reloadable - can use pg_reload_conf)\nALTER SYSTEM SET autovacuum = on;\n\n-- Reload config (ONLY works for parameters that don't require restart)\n-- This will NOT reload shared_buffers - restart required for that!\nSELECT pg_reload_conf();\n```\n\n### MySQL Config\n\n```ini\n# my.cnf\n[mysqld]\ninnodb_buffer_pool_size = 8G  # 70% of RAM\nmax_connections = 500\nslow_query_log = 1\nlong_query_time = 1\n```\n\n---\n\n## When to Load References\n\n**Performance Analysis**:\n- Load `references\u002Fexplain-analysis.md` when: Reading EXPLAIN output, understanding query plans, analyzing buffer statistics, comparing PostgreSQL vs MySQL EXPLAIN\n- Load `references\u002Fperformance-monitoring.md` when: Setting up monitoring, tracking slow queries over time, monitoring cache hit ratios, identifying bloated tables\n\n**Index Optimization**:\n- Load `references\u002Findex-strategies.md` when: Choosing index type (B-Tree, GIN, GiST, Hash), creating composite indexes, determining column order, using covering indexes, implementing partial indexes, monitoring index usage\n\n**Query Optimization**:\n- Load `references\u002Fquery-rewrites.md` when: Rewriting slow queries, converting subqueries to JOINs, eliminating N+1 queries, implementing pagination, optimizing LIKE queries, batching operations\n\n**Systematic Process**:\n- Load `references\u002Foptimization-workflow.md` when: Following step-by-step optimization process, creating optimization hypothesis, measuring improvements, monitoring long-term performance\n\n**Error Resolution**:\n- Load `references\u002Ferror-catalog.md` when: Debugging specific errors (sequential scans, missing indexes, N+1 queries, etc.), understanding root causes, implementing verified solutions\n\n---\n\n## Using Bundled Resources\n\n### Templates (Copy-Paste SQL)\n\n```bash\n# EXPLAIN query templates\ntemplates\u002Fexplain-query.sql\n\n# Index creation patterns\ntemplates\u002Findex-examples.sql\n\n# Query rewrite examples\ntemplates\u002Fquery-rewrites.sql\n\n# Monitoring queries\ntemplates\u002Fmonitoring-queries.sql\n```\n\n### References (Deep Dives)\n\n```bash\n# Comprehensive guides\nreferences\u002Ferror-catalog.md              # All 12 errors + solutions\nreferences\u002Fexplain-analysis.md           # Reading query plans\nreferences\u002Findex-strategies.md           # Index types & selection\nreferences\u002Fquery-rewrites.md             # Before\u002Fafter optimizations\nreferences\u002Fperformance-monitoring.md     # Long-term monitoring\nreferences\u002Foptimization-workflow.md      # Systematic process\n```\n\n---\n\n## Dependencies\n\n**PostgreSQL Extensions**:\n- `pg_stat_statements` - Query performance tracking (built-in)\n- `pg_trgm` - Trigram similarity search (optional, for fuzzy matching)\n\n**MySQL**:\n- `performance_schema` - Performance monitoring (enabled by default in 8.0+)\n\n**No additional dependencies required.**\n\n---\n\n## Known Issues Prevention\n\n| Issue | Symptom | Prevention |\n|-------|---------|------------|\n| Sequential scans | Seq Scan on 1M+ rows | Index filter columns before production |\n| Missing FK indexes | Slow JOINs | Always index foreign keys |\n| N+1 queries | 1+N database calls | Use JOIN or eager loading |\n| Leading wildcards | LIKE '%x%' slow | Use full-text search (GIN) |\n| SELECT * bloat | High network traffic | Select specific columns |\n| No LIMIT | Memory exhaustion | Always LIMIT unbounded queries |\n| Stale statistics | Wrong query plans | ANALYZE after bulk operations |\n| Wrong index order | Index exists but not used | Match query pattern |\n| Missing composite | Multiple WHERE slow | Create composite index |\n| No connection pool | High latency | Implement pooling (20-50 connections) |\n| SQL injection | Security vulnerability | Use prepared statements only |\n| Temp spills | Disk I\u002FO on sorts | Increase work_mem |\n\n---\n\n## Complete Setup Checklist\n\nProduction Deployment:\n- [ ] Enable pg_stat_statements or performance_schema\n- [ ] Index all foreign key columns\n- [ ] Index columns in WHERE, JOIN, ORDER BY clauses\n- [ ] Replace SELECT * with specific columns\n- [ ] Add LIMIT to all unbounded queries\n- [ ] Use prepared statements (parameterized queries)\n- [ ] Implement connection pooling (20-50 connections)\n- [ ] Configure work_mem (256MB-1GB per connection)\n- [ ] Configure shared_buffers (25% of RAM for PostgreSQL)\n- [ ] Enable slow query logging (threshold: 100-1000ms)\n- [ ] Run EXPLAIN ANALYZE on all critical queries\n- [ ] Set up daily monitoring of pg_stat_statements\n- [ ] Schedule ANALYZE after nightly bulk operations\n- [ ] Monitor cache hit ratio (target: >99%)\n- [ ] Review and drop unused indexes monthly\n\n---\n\n## Production Example\n\n**Before Optimization**:\n```sql\n-- Query: Fetch user orders\nSELECT * FROM orders WHERE user_id = 123;\n\n-- Performance:\n-- Execution time: 2500ms\n-- Seq Scan on orders (1M rows scanned)\n-- Network: 50MB transferred\n-- No index on user_id\n```\n\n**After Optimization**:\n```sql\n-- Add index\nCREATE INDEX CONCURRENTLY idx_orders_user_id ON orders(user_id);\n\n-- Optimize query\nSELECT id, total, status, created_at\nFROM orders\nWHERE user_id = 123\nLIMIT 100;\n\n-- Performance:\n-- Execution time: 12ms (208x faster!)\n-- Index Scan using idx_orders_user_id (100 rows)\n-- Network: 50KB transferred (1000x less!)\n-- Covering index with INCLUDE\n```\n\n**Result**: 208x faster execution, 1000x less data transfer\n\n---\n\n**For comprehensive optimization guidance, error resolution, and production patterns, load the appropriate reference files listed in \"When to Load References\" above.**\n",{"name":5,"license":15,"metadata":24,"description":7},{"keywords":25},[26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58],"sql optimization","query performance","database indexes","explain analyze","slow queries","n+1 problem","query plan","index strategy","composite index","covering index","postgresql performance","mysql optimization","query rewriting","prepared statements","connection pooling","sequential scan","missing index","SELECT *","LIMIT optimization","subquery performance","pagination","cursor based pagination","batch operations","pg_stat_statements","full-text search","bitmap scan","index only scan","query tuning","database performance","cache hit ratio","work_mem","shared_buffers","database monitoring","main","c475fc64e94e803b50d14a791dfee8853fbb2c5c","integrations\u002Fclaude-skills-secondsky\u002Fplugins\u002Fsql-query-optimization\u002Fskills\u002Fsql-query-optimization","https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory","https:\u002F\u002Fgithub.com\u002FElogic360","2026-11-08 22:21:22",{"source":8,"skillName":5,"commands":66,"prompt":76,"zipAvailable":77},[67,70,73],{"tool":68,"command":69},"npx","npx skills add Elogic360\u002Fsoftware-factory --skill sql-query-optimization",{"tool":71,"command":72},"bunx","bunx skills add Elogic360\u002Fsoftware-factory --skill sql-query-optimization",{"tool":74,"command":75},"pnpm","pnpm dlx skills add Elogic360\u002Fsoftware-factory --skill sql-query-optimization","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fintegrations\u002Fclaude-skills-secondsky\u002Fplugins\u002Fsql-query-optimization\u002Fskills\u002Fsql-query-optimization\u002FSKILL.md",true,[79,85,89,93,97,101,105,111,115,119],{"path":80,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":83,"sourceHtmlUrl":84},"references\u002Ferror-catalog.md","REFERENCE","参考文档",13700,"https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fintegrations\u002Fclaude-skills-secondsky\u002Fplugins\u002Fsql-query-optimization\u002Fskills\u002Fsql-query-optimization\u002Freferences\u002Ferror-catalog.md",{"path":86,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":87,"sourceHtmlUrl":88},"references\u002Fexplain-analysis.md",10794,"https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fintegrations\u002Fclaude-skills-secondsky\u002Fplugins\u002Fsql-query-optimization\u002Fskills\u002Fsql-query-optimization\u002Freferences\u002Fexplain-analysis.md",{"path":90,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":91,"sourceHtmlUrl":92},"references\u002Findex-strategies.md",11372,"https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fintegrations\u002Fclaude-skills-secondsky\u002Fplugins\u002Fsql-query-optimization\u002Fskills\u002Fsql-query-optimization\u002Freferences\u002Findex-strategies.md",{"path":94,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":95,"sourceHtmlUrl":96},"references\u002Foptimization-workflow.md",5193,"https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fintegrations\u002Fclaude-skills-secondsky\u002Fplugins\u002Fsql-query-optimization\u002Fskills\u002Fsql-query-optimization\u002Freferences\u002Foptimization-workflow.md",{"path":98,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":99,"sourceHtmlUrl":100},"references\u002Fperformance-monitoring.md",4639,"https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fintegrations\u002Fclaude-skills-secondsky\u002Fplugins\u002Fsql-query-optimization\u002Fskills\u002Fsql-query-optimization\u002Freferences\u002Fperformance-monitoring.md",{"path":102,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":103,"sourceHtmlUrl":104},"references\u002Fquery-rewrites.md",3234,"https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fintegrations\u002Fclaude-skills-secondsky\u002Fplugins\u002Fsql-query-optimization\u002Fskills\u002Fsql-query-optimization\u002Freferences\u002Fquery-rewrites.md",{"path":106,"resourceType":107,"resourceTypeDesc":108,"sizeBytes":109,"sourceHtmlUrl":110},"templates\u002Fexplain-query.sql","OTHER","其他",911,"https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fintegrations\u002Fclaude-skills-secondsky\u002Fplugins\u002Fsql-query-optimization\u002Fskills\u002Fsql-query-optimization\u002Ftemplates\u002Fexplain-query.sql",{"path":112,"resourceType":107,"resourceTypeDesc":108,"sizeBytes":113,"sourceHtmlUrl":114},"templates\u002Findex-examples.sql",1049,"https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fintegrations\u002Fclaude-skills-secondsky\u002Fplugins\u002Fsql-query-optimization\u002Fskills\u002Fsql-query-optimization\u002Ftemplates\u002Findex-examples.sql",{"path":116,"resourceType":107,"resourceTypeDesc":108,"sizeBytes":117,"sourceHtmlUrl":118},"templates\u002Fmonitoring-queries.sql",3384,"https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fintegrations\u002Fclaude-skills-secondsky\u002Fplugins\u002Fsql-query-optimization\u002Fskills\u002Fsql-query-optimization\u002Ftemplates\u002Fmonitoring-queries.sql",{"path":120,"resourceType":107,"resourceTypeDesc":108,"sizeBytes":121,"sourceHtmlUrl":122},"templates\u002Fquery-rewrites.sql",2557,"https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fintegrations\u002Fclaude-skills-secondsky\u002Fplugins\u002Fsql-query-optimization\u002Fskills\u002Fsql-query-optimization\u002Ftemplates\u002Fquery-rewrites.sql",[124,132,139,146,153,160],{"skillNo":125,"name":126,"nameZh":6,"description":127,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":128,"licenseFileUrl":6,"sourceHtmlUrl":129,"categories":130,"keywords":131,"publishedAt":19},"01M79G206MT3J6S0GY3C45P2KV","vss-summarize-video","Use to summarize a recorded video via the LVS summarization microservice (HITL-gated) with a VLM fallback. Not for report generation or live RTSP captioning.","Apache-2.0","https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fskills\u002Fnvidia\u002Fvss-summarize-video\u002FSKILL.md",[],[],{"skillNo":133,"name":134,"nameZh":6,"description":135,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":128,"licenseFileUrl":6,"sourceHtmlUrl":136,"categories":137,"keywords":138,"publishedAt":19},"01M79G1WN63PGRE8CKD47WEBQ5","vss-setup-video-analytics-api","Use to deploy the vss-video-analytics-api REST service standalone (config-source, data-log bind, Elasticsearch, optional Kafka). Not for full warehouse deploy.","https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fskills\u002Fnvidia\u002Fvss-setup-video-analytics-api\u002FSKILL.md",[],[],{"skillNo":140,"name":141,"nameZh":6,"description":142,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":128,"licenseFileUrl":6,"sourceHtmlUrl":143,"categories":144,"keywords":145,"publishedAt":19},"01M79G1S9F7VY3EF6H53PRP5AN","vss-setup-behavior-analytics","Use to deploy the vss-behavior-analytics service standalone (entrypoint, config-source, optional calibration). Not for the full warehouse deploy.","https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fskills\u002Fnvidia\u002Fvss-setup-behavior-analytics\u002FSKILL.md",[],[],{"skillNo":147,"name":148,"nameZh":6,"description":149,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":128,"licenseFileUrl":6,"sourceHtmlUrl":150,"categories":151,"keywords":152,"publishedAt":19},"01M79G1N1S1Y27PFZPYMNK1MTQ","vss-search-archive","Use this skill to run top-level VSS fusion search on archived video, or to ingest video files \u002F RTSP streams for search. Do NOT use for ad-hoc visual Q&A (use vss-ask-video), live captioning (use vss-deploy-dense-captioning), or video summarization and reports (use vss-summarize-video).","https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fskills\u002Fnvidia\u002Fvss-search-archive\u002FSKILL.md",[],[],{"skillNo":154,"name":155,"nameZh":6,"description":156,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":128,"licenseFileUrl":6,"sourceHtmlUrl":157,"categories":158,"keywords":159,"publishedAt":19},"01M79G1H6WN0Q6C0VCAXCZX6B7","vss-query-analytics","Use this skill when reading video-analytics metrics, incidents, alerts, and sensor data via the VA-MCP server (port 9901). Not for live VLM or incident-range narrative reports.","https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fskills\u002Fnvidia\u002Fvss-query-analytics\u002FSKILL.md",[],[],{"skillNo":161,"name":162,"nameZh":6,"description":163,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":128,"licenseFileUrl":6,"sourceHtmlUrl":164,"categories":165,"keywords":166,"publishedAt":19},"01M79G1DYPNXQS7QHZ0AAF5FX5","vss-manage-video-io-storage","Use to call the VIOS REST API (sensor list, timelines, clip extraction, snapshots, add\u002Fdelete sensors and streams). Not for VLM inference or search.","https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fskills\u002Fnvidia\u002Fvss-manage-video-io-storage\u002FSKILL.md",[],[]]