Master SQL query optimization, indexing strategies

SQL optimization patterns

by wshobson · MIT license · ★ 39,857 on GitHub · updated Sep 21

SQL optimization patterns cover

Master SQL query optimization, indexing strategies, and EXPLAIN analysis to dramatically improve database performance and eliminate slow queries. Use when debugging slow queries, designing database schemas, or optimizing application…

---
name: sql-optimization-patterns
description: Master SQL query optimization, indexing strategies, and EXPLAIN analysis to dramatically improve database performance and eliminate slow queries. Use when debugging slow queries, designing database schemas, or optimizing application performance.
---

# SQL Optimization Patterns

Transform slow database queries into lightning-fast operations through systematic optimization, proper indexing, and query plan analysis.

## When to Use This Skill

- Debugging slow-running queries
- Designing performant database schemas
- Optimizing application response times
- Reducing database load and costs
- Improving scalability for growing datasets
- Analyzing EXPLAIN query plans
- Implementing efficient indexes

Overview

Transform slow database queries into lightning-fast operations through systematic optimization, proper indexing, and query plan analysis.

Manual install (npx, ZIP)
Claude Codenpx skills add wshobson/agents --skill sql-optimization-patterns -g -a claude-code
Claude Code (manual)mkdir -p ~/.claude/skills && curl -sL https://codeload.github.com/wshobson/agents/tar.gz/4236bb91f839 \ | tar -xz -C ~/.claude/skills --strip-components=4 agents-4236bb91f839/plugins/developer-essentials/skills/sql-optimization-patterns
Windows (PowerShell)New-Item -ItemType Directory -Force "$HOME\.claude\skills" | Out-Null; Invoke-WebRequest "https://m.agentalley.io/zip/f3b53fb7ee78ad1b59f3/sql-optimization-patterns.zip" -OutFile "$env:TEMP\sql-optimization-patterns.zip"; Expand-Archive "$env:TEMP\sql-optimization-patterns.zip" -DestinationPath "$HOME\.claude\skills" -Force
Claude.ai / desktopDownload the ZIP and upload it under Settings → Capabilities → Skills.
Codex, Cursor, other agentsPoint them at SKILL.md. The other files are plain text.

Connects with Agent Alley MCP · agentalley.io/mcp

Files included

  • SKILL.md5.8 KB
  • references/1 file · 6.7 KB
Read the files here
wshobson/4236bb92 files
SKILL.md
Show the full text215 lines

SQL Optimization Patterns

Transform slow database queries into lightning-fast operations through systematic optimization, proper indexing, and query plan analysis.

When to Use This Skill

  • Debugging slow-running queries
  • Designing performant database schemas
  • Optimizing application response times
  • Reducing database load and costs
  • Improving scalability for growing datasets
  • Analyzing EXPLAIN query plans
  • Implementing efficient indexes
  • Resolving N+1 query problems

Core Concepts

1. Query Execution Plans (EXPLAIN)

Understanding EXPLAIN output is fundamental to optimization.

PostgreSQL EXPLAIN:

-- Basic explain
EXPLAIN SELECT * FROM users WHERE email = '[email protected]';

-- With actual execution stats
EXPLAIN ANALYZE
SELECT * FROM users WHERE email = '[email protected]';

-- Verbose output with more details
EXPLAIN (ANALYZE, BUFFERS, VERBOSE)
SELECT u.*, o.order_total
FROM users u
JOIN orders o ON u.id = o.user_id
WHERE u.created_at > NOW() - INTERVAL '30 days';

Key Metrics to Watch:

  • Seq Scan: Full table scan (usually slow for large tables)
  • Index Scan: Using index (good)
  • Index Only Scan: Using index without touching table (best)
  • Nested Loop: Join method (okay for small datasets)
  • Hash Join: Join method (good for larger datasets)
  • Merge Join: Join method (good for sorted data)
  • Cost: Estimated query cost (lower is better)
  • Rows: Estimated rows returned
  • Actual Time: Real execution time
2. Index Strategies

Indexes are the most powerful optimization tool.

Index Types:

  • B-Tree: Default, good for equality and range queries
  • Hash: Only for equality (=) comparisons
  • GIN: Full-text search, array queries, JSONB
  • GiST: Geometric data, full-text search
  • BRIN: Block Range INdex for very large tables with correlation
-- Standard B-Tree index
CREATE INDEX idx_users_email ON users(email);

-- Composite index (order matters!)
CREATE INDEX idx_orders_user_status ON orders(user_id, status);

-- Partial index (index subset of rows)
CREATE INDEX idx_active_users ON users(email)
WHERE status = 'active';

-- Expression index
CREATE INDEX idx_users_lower_email ON users(LOWER(email));

-- Covering index (include additional columns)
CREATE INDEX idx_users_email_covering ON users(email)
INCLUDE (name, created_at);

-- Full-text search index
CREATE INDEX idx_posts_search ON posts
USING GIN(to_tsvector('english', title || ' ' || body));

-- JSONB index
CREATE INDEX idx_metadata ON events USING GIN(metadata);
3. Query Optimization Patterns

Avoid SELECT *:

-- Bad: Fetches unnecessary columns
SELECT * FROM users WHERE id = 123;

-- Good: Fetch only what you need
SELECT id, email, name FROM users WHERE id = 123;

Use WHERE Clause Efficiently:

-- Bad: Function prevents index usage
SELECT * FROM users WHERE LOWER(email) = '[email protected]';

-- Good: Create functional index or use exact match
CREATE INDEX idx_users_email_lower ON users(LOWER(email));
-- Then:
SELECT * FROM users WHERE LOWER(email) = '[email protected]';

-- Or store normalized data
SELECT * FROM users WHERE email = '[email protected]';

Optimize JOINs:

-- Bad: Cartesian product then filter
SELECT u.name, o.total
FROM users u, orders o
WHERE u.id = o.user_id AND u.created_at > '2024-01-01';

-- Good: Filter before join
SELECT u.name, o.total
FROM users u
JOIN orders o ON u.id = o.user_id
WHERE u.created_at > '2024-01-01';

-- Better: Filter both tables
SELECT u.name, o.total
FROM (SELECT * FROM users WHERE created_at > '2024-01-01') u
JOIN orders o ON u.id = o.user_id;

Detailed patterns and worked examples

Detailed pattern documentation lives in references/details.md. Read that file when the navigation tier above is insufficient.

Best Practices

  1. Index Selectively: Too many indexes slow down writes
  2. Monitor Query Performance: Use slow query logs
  3. Keep Statistics Updated: Run ANALYZE regularly
  4. Use Appropriate Data Types: Smaller types = better performance
  5. Normalize Thoughtfully: Balance normalization vs performance
  6. Cache Frequently Accessed Data: Use application-level caching
  7. Connection Pooling: Reuse database connections
  8. Regular Maintenance: VACUUM, ANALYZE, rebuild indexes
-- Update statistics
ANALYZE users;
ANALYZE VERBOSE orders;

-- Vacuum (PostgreSQL)
VACUUM ANALYZE users;
VACUUM FULL users;  -- Reclaim space (locks table)

-- Reindex
REINDEX INDEX idx_users_email;
REINDEX TABLE users;

Common Pitfalls

  • Over-Indexing: Each index slows down INSERT/UPDATE/DELETE
  • Unused Indexes: Waste space and slow writes
  • Missing Indexes: Slow queries, full table scans
  • Implicit Type Conversion: Prevents index usage
  • OR Conditions: Can't use indexes efficiently
  • LIKE with Leading Wildcard: LIKE '%abc' can't use index
  • Function in WHERE: Prevents index usage unless functional index exists

Monitoring Queries

-- Find slow queries (PostgreSQL)
SELECT query, calls, total_time, mean_time
FROM pg_stat_statements
ORDER BY mean_time DESC
LIMIT 10;

-- Find missing indexes (PostgreSQL)
SELECT
    schemaname,
    tablename,
    seq_scan,
    seq_tup_read,
    idx_scan,
    seq_tup_read / seq_scan AS avg_seq_tup_read
FROM pg_stat_user_tables
WHERE seq_scan > 0
ORDER BY seq_tup_read DESC
LIMIT 10;

-- Find unused indexes (PostgreSQL)
SELECT
    schemaname,
    tablename,
    indexname,
    idx_scan,
    idx_tup_read,
    idx_tup_fetch
FROM pg_stat_user_indexes
WHERE idx_scan = 0
ORDER BY pg_relation_size(indexrelid) DESC;
1---
2name: sql-optimization-patterns
3description: Master SQL query optimization, indexing strategies, and EXPLAIN analysis to dramatically improve database performance and eliminate slow queries. Use when debugging slow queries, designing database schemas, or optimizing application performance.
4---
5 
6# SQL Optimization Patterns
7 
8Transform slow database queries into lightning-fast operations through systematic optimization, proper indexing, and query plan analysis.
9 
10## When to Use This Skill
11 
12- Debugging slow-running queries
13- Designing performant database schemas
14- Optimizing application response times
15- Reducing database load and costs
16- Improving scalability for growing datasets
17- Analyzing EXPLAIN query plans
18- Implementing efficient indexes
19- Resolving N+1 query problems
20 
21## Core Concepts
22 
23### 1. Query Execution Plans (EXPLAIN)
24 
25Understanding EXPLAIN output is fundamental to optimization.
26 
27**PostgreSQL EXPLAIN:**
28 
29```sql
30-- Basic explain
31EXPLAIN SELECT * FROM users WHERE email = '[email protected]';
32 
33-- With actual execution stats
34EXPLAIN ANALYZE
35SELECT * FROM users WHERE email = '[email protected]';
36 
37-- Verbose output with more details
38EXPLAIN (ANALYZE, BUFFERS, VERBOSE)
39SELECT u.*, o.order_total
40FROM users u
41JOIN orders o ON u.id = o.user_id
42WHERE u.created_at > NOW() - INTERVAL '30 days';
43```
44 
45**Key Metrics to Watch:**
46 
47- **Seq Scan**: Full table scan (usually slow for large tables)
48- **Index Scan**: Using index (good)
49- **Index Only Scan**: Using index without touching table (best)
50- **Nested Loop**: Join method (okay for small datasets)
51- **Hash Join**: Join method (good for larger datasets)
52- **Merge Join**: Join method (good for sorted data)
53- **Cost**: Estimated query cost (lower is better)
54- **Rows**: Estimated rows returned
55- **Actual Time**: Real execution time
56 
57### 2. Index Strategies
58 
59Indexes are the most powerful optimization tool.
60 
61**Index Types:**
62 
63- **B-Tree**: Default, good for equality and range queries
64- **Hash**: Only for equality (=) comparisons
65- **GIN**: Full-text search, array queries, JSONB
66- **GiST**: Geometric data, full-text search
67- **BRIN**: Block Range INdex for very large tables with correlation
68 
69```sql
70-- Standard B-Tree index
71CREATE INDEX idx_users_email ON users(email);
72 
73-- Composite index (order matters!)
74CREATE INDEX idx_orders_user_status ON orders(user_id, status);
75 
76-- Partial index (index subset of rows)
77CREATE INDEX idx_active_users ON users(email)
78WHERE status = 'active';
79 
80-- Expression index
81CREATE INDEX idx_users_lower_email ON users(LOWER(email));
82 
83-- Covering index (include additional columns)
84CREATE INDEX idx_users_email_covering ON users(email)
85INCLUDE (name, created_at);
86 
87-- Full-text search index
88CREATE INDEX idx_posts_search ON posts
89USING GIN(to_tsvector('english', title || ' ' || body));
90 
91-- JSONB index
92CREATE INDEX idx_metadata ON events USING GIN(metadata);
93```
94 
95### 3. Query Optimization Patterns
96 
97**Avoid SELECT \*:**
98 
99```sql
100-- Bad: Fetches unnecessary columns
101SELECT * FROM users WHERE id = 123;
102 
103-- Good: Fetch only what you need
104SELECT id, email, name FROM users WHERE id = 123;
105```
106 
107**Use WHERE Clause Efficiently:**
108 
109```sql
110-- Bad: Function prevents index usage
111SELECT * FROM users WHERE LOWER(email) = '[email protected]';
112 
113-- Good: Create functional index or use exact match
114CREATE INDEX idx_users_email_lower ON users(LOWER(email));
115-- Then:
116SELECT * FROM users WHERE LOWER(email) = '[email protected]';
117 
118-- Or store normalized data
119SELECT * FROM users WHERE email = '[email protected]';
120```
121 
122**Optimize JOINs:**
123 
124```sql
125-- Bad: Cartesian product then filter
126SELECT u.name, o.total
127FROM users u, orders o
128WHERE u.id = o.user_id AND u.created_at > '2024-01-01';
129 
130-- Good: Filter before join
131SELECT u.name, o.total
132FROM users u
133JOIN orders o ON u.id = o.user_id
134WHERE u.created_at > '2024-01-01';
135 
136-- Better: Filter both tables
137SELECT u.name, o.total
138FROM (SELECT * FROM users WHERE created_at > '2024-01-01') u
139JOIN orders o ON u.id = o.user_id;
140```
141 
142## Detailed patterns and worked examples
143 
144Detailed pattern documentation lives in `references/details.md`. Read that file when the navigation tier above is insufficient.
145 
146## Best Practices
147 
1481. **Index Selectively**: Too many indexes slow down writes
1492. **Monitor Query Performance**: Use slow query logs
1503. **Keep Statistics Updated**: Run ANALYZE regularly
1514. **Use Appropriate Data Types**: Smaller types = better performance
1525. **Normalize Thoughtfully**: Balance normalization vs performance
1536. **Cache Frequently Accessed Data**: Use application-level caching
1547. **Connection Pooling**: Reuse database connections
1558. **Regular Maintenance**: VACUUM, ANALYZE, rebuild indexes
156 
157```sql
158-- Update statistics
159ANALYZE users;
160ANALYZE VERBOSE orders;
161 
162-- Vacuum (PostgreSQL)
163VACUUM ANALYZE users;
164VACUUM FULL users; -- Reclaim space (locks table)
165 
166-- Reindex
167REINDEX INDEX idx_users_email;
168REINDEX TABLE users;
169```
170 
171## Common Pitfalls
172 
173- **Over-Indexing**: Each index slows down INSERT/UPDATE/DELETE
174- **Unused Indexes**: Waste space and slow writes
175- **Missing Indexes**: Slow queries, full table scans
176- **Implicit Type Conversion**: Prevents index usage
177- **OR Conditions**: Can't use indexes efficiently
178- **LIKE with Leading Wildcard**: `LIKE '%abc'` can't use index
179- **Function in WHERE**: Prevents index usage unless functional index exists
180 
181## Monitoring Queries
182 
183```sql
184-- Find slow queries (PostgreSQL)
185SELECT query, calls, total_time, mean_time
186FROM pg_stat_statements
187ORDER BY mean_time DESC
188LIMIT 10;
189 
190-- Find missing indexes (PostgreSQL)
191SELECT
192 schemaname,
193 tablename,
194 seq_scan,
195 seq_tup_read,
196 idx_scan,
197 seq_tup_read / seq_scan AS avg_seq_tup_read
198FROM pg_stat_user_tables
199WHERE seq_scan > 0
200ORDER BY seq_tup_read DESC
201LIMIT 10;
202 
203-- Find unused indexes (PostgreSQL)
204SELECT
205 schemaname,
206 tablename,
207 indexname,
208 idx_scan,
209 idx_tup_read,
210 idx_tup_fetch
211FROM pg_stat_user_indexes
212WHERE idx_scan = 0
213ORDER BY pg_relation_size(indexrelid) DESC;
214```
215 
View all files on GitHub →

Details

Updated
Sep 21, 2026
License
MIT
Stars on the repo
★ 39,857
Checked
Source
wshobson/agents ↗
Creator
wshobson · 179 listings
View creator

Similar skills

See all →
SkillDiagnose why a specific ad creative is winning or losingCreative performance analysisgmmh1/claude-paid-media-skills · by gmmh1Diagnose why a specific ad creative is winning or losing using the generalized hook-hold-click-convert funnel, applicable across any platform. Triggers on 'why is this ad underperforming', 'diagnose my creative', or 'where in the funnel is this ad failing'. Platform-agnostic diagnostic framework — platform-specific versions (meta-ads-creative-analytics) apply this with platform-native metrics.New listingPromptAct as a professional full-stack developer taskedProfessional Full-Stack Developer for Network Mapping & Monitoring Applicationf/prompts.chat · by Yohanes Farly RakinaungAct as a professional full-stack developer tasked with building a web application for mapping and monitoring networks using Mikrotik Netwatch API. Implement multi-user role-based management to handle devices, monitor their status, and manage user subscriptions.New listingSkillEstablishes a project's quality bar as a written contractConstraint driven developmentaddyosmani/agent-skills · by addyosmaniEstablishes a project's quality bar as a written contract and stops agents quietly lowering it. Interviews the user on which dimensions matter, supplies sane default thresholds when they have no number in mind, records everything in CONSTRAINTS.md, and watches the diff for a weakened bar — new @ts-ignore or eslint-disable suppressions, skipped or deleted tests, assertions stripped out, unimplemented stubs, thresholds edited down. Use when no quality bar is written down, when the user says "set up constraints" or "define our standards", when the user wants dimensions they care about — accessibility, web performance, coverage — set up as enforced constraints, when an agent keeps silencing checks or skipping tests to get to green, when you need a coverage or performance threshold and don't know what number to pick, or when an agent writes more code than anyone will read.★ 98.7k GitHub starsSkillInstruments code so production behavior is visibleObservability and instrumentationaddyosmani/agent-skills · by addyosmaniInstruments code so production behavior is visible and diagnosable. Use when adding logging, metrics, tracing, or alerting. Use when shipping any feature that runs in production and you need evidence it works. Use when production issues are reported but you can't tell what happened from the available data.★ 98.7k GitHub starsSkillOptimizes application performance across frontend, backendPerformance optimizationaddyosmani/agent-skills · by addyosmaniOptimizes application performance across frontend, backend, queries, and databases. Use when performance requirements exist, when you suspect performance regressions, when Core Web Vitals or load times need improvement, when N+1 query patterns need fixing, or when profiling reveals bottlenecks.★ 98.7k GitHub starsSkillDiscovers and invokes agent skillsUsing agent skillsaddyosmani/agent-skills · by addyosmaniDiscovers and invokes agent skills. Use when starting a session, or when you need to decide which skill or workflow applies to the piece of work at hand. This is the meta-skill that governs how all other skills are discovered and invoked.★ 98.7k GitHub stars

More from wshobson

SkillMaster C/.NET backend development patterns for buildingwshobson/agents · by wshobsonMaster C#/.NET backend development patterns for building robust APIs, MCP servers, and enterprise applications. Covers async/await, dependency injection, Entity Framework Core, Dapper, configuration, caching, and testing with xUnit. Use when developing .NET backends, reviewing C# code, or designing API architectures.★ 39.9k GitHub starsSkillImplement WCAG 2.2 compliant interfaces with mobileAccessibility compliancewshobson/agents · by wshobsonImplement WCAG 2.2 compliant interfaces with mobile accessibility, inclusive design patterns, and assistive technology support. Use when auditing accessibility, implementing ARIA patterns, building for screen readers, or ensuring inclusive user experiences.★ 39.9k GitHub starsSkillMaster Material Design 3 and Jetpack Compose patternsAndroid Mobile Designwshobson/agents · by wshobsonMaster Material Design 3 and Jetpack Compose patterns for building native Android apps. Use when designing Android interfaces, implementing Compose UI, or following Google's Material Design guidelines.★ 39.9k GitHub starsSkillMigrate from AngularJS to Angular using hybrid modeAngular migrationwshobson/agents · by wshobsonMigrate from AngularJS to Angular using hybrid mode, incremental component rewriting, and dependency injection updates. Use when upgrading AngularJS applications, planning framework migrations, or modernizing legacy Angular code.★ 39.9k GitHub starsSkillUnderstand anti-reversing, obfuscationAnti reversing techniqueswshobson/agents · by wshobsonUnderstand anti-reversing, obfuscation, and protection techniques encountered during software analysis. Use this skill when analyzing malware evasion techniques, when implementing anti-debugging protections for CTF challenges, when reverse engineering packed binaries, or when building security research tools that need to detect virtualized environments.★ 39.9k GitHub starsSkillBuild production Apache Airflow DAGs with best practicesApache Airflow DAG Patternswshobson/agents · by wshobsonBuild production Apache Airflow DAGs with best practices for operators, sensors, testing, and deployment. Use when creating data pipelines, orchestrating workflows, or scheduling batch jobs.★ 39.9k GitHub stars