@zimezone/z-command 1.1.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (182) hide show
  1. package/package.json +4 -1
  2. package/templates/agents/api-documenter.agent.md +161 -0
  3. package/templates/agents/architect-review.agent.md +146 -0
  4. package/templates/agents/arm-cortex-expert.agent.md +288 -0
  5. package/templates/agents/backend-architect.agent.md +309 -0
  6. package/templates/agents/backend-security-coder.agent.md +152 -0
  7. package/templates/agents/bash-pro.agent.md +285 -0
  8. package/templates/agents/c-pro.agent.md +35 -0
  9. package/templates/agents/c4-code.agent.md +320 -0
  10. package/templates/agents/c4-component.agent.md +227 -0
  11. package/templates/agents/c4-container.agent.md +248 -0
  12. package/templates/agents/c4-context.agent.md +235 -0
  13. package/templates/agents/conductor-validator.agent.md +245 -0
  14. package/templates/agents/csharp-pro.agent.md +38 -0
  15. package/templates/agents/customer-support.agent.md +148 -0
  16. package/templates/agents/database-admin.agent.md +142 -0
  17. package/templates/agents/database-architect.agent.md +238 -0
  18. package/templates/agents/database-optimizer.agent.md +144 -0
  19. package/templates/agents/debugger.agent.md +30 -0
  20. package/templates/agents/deployment-engineer.agent.md +0 -0
  21. package/templates/agents/devops-troubleshooter.agent.md +138 -0
  22. package/templates/agents/django-pro.agent.md +159 -0
  23. package/templates/agents/docs-architect.agent.md +77 -0
  24. package/templates/agents/dotnet-architect.agent.md +175 -0
  25. package/templates/agents/dx-optimizer.agent.md +63 -0
  26. package/templates/agents/elixir-pro.agent.md +38 -0
  27. package/templates/agents/error-detective.agent.md +32 -0
  28. package/templates/agents/event-sourcing-architect.agent.md +42 -0
  29. package/templates/agents/fastapi-pro.agent.md +171 -0
  30. package/templates/agents/firmware-analyst.agent.md +330 -0
  31. package/templates/agents/frontend-security-coder.agent.md +149 -0
  32. package/templates/agents/haskell-pro.agent.md +37 -0
  33. package/templates/agents/hr-pro.agent.md +105 -0
  34. package/templates/agents/incident-responder.agent.md +190 -0
  35. package/templates/agents/ios-developer.agent.md +198 -0
  36. package/templates/agents/java-pro.agent.md +156 -0
  37. package/templates/agents/javascript-pro.agent.md +35 -0
  38. package/templates/agents/julia-pro.agent.md +187 -0
  39. package/templates/agents/legal-advisor.agent.md +49 -0
  40. package/templates/agents/malware-analyst.agent.md +272 -0
  41. package/templates/agents/mermaid-expert.agent.md +39 -0
  42. package/templates/agents/minecraft-bukkit-pro.agent.md +104 -0
  43. package/templates/agents/mobile-security-coder.agent.md +163 -0
  44. package/templates/agents/monorepo-architect.agent.md +44 -0
  45. package/templates/agents/observability-engineer.agent.md +228 -0
  46. package/templates/agents/performance-engineer.agent.md +167 -0
  47. package/templates/agents/php-pro.agent.md +43 -0
  48. package/templates/agents/posix-shell-pro.agent.md +284 -0
  49. package/templates/agents/quant-analyst.agent.md +32 -0
  50. package/templates/agents/reference-builder.agent.md +167 -0
  51. package/templates/agents/reverse-engineer.agent.md +202 -0
  52. package/templates/agents/risk-manager.agent.md +41 -0
  53. package/templates/agents/ruby-pro.agent.md +35 -0
  54. package/templates/agents/rust-pro.agent.md +156 -0
  55. package/templates/agents/sales-automator.agent.md +35 -0
  56. package/templates/agents/scala-pro.agent.md +60 -0
  57. package/templates/agents/search-specialist.agent.md +59 -0
  58. package/templates/agents/security-auditor.agent.md +138 -0
  59. package/templates/agents/seo-authority-builder.agent.md +116 -0
  60. package/templates/agents/seo-cannibalization-detector.agent.md +103 -0
  61. package/templates/agents/seo-content-auditor.agent.md +63 -0
  62. package/templates/agents/seo-content-planner.agent.md +88 -0
  63. package/templates/agents/seo-content-refresher.agent.md +98 -0
  64. package/templates/agents/seo-content-writer.agent.md +76 -0
  65. package/templates/agents/seo-keyword-strategist.agent.md +75 -0
  66. package/templates/agents/seo-meta-optimizer.agent.md +72 -0
  67. package/templates/agents/seo-snippet-hunter.agent.md +94 -0
  68. package/templates/agents/seo-structure-architect.agent.md +88 -0
  69. package/templates/agents/service-mesh-expert.agent.md +41 -0
  70. package/templates/agents/sql-pro.agent.md +146 -0
  71. package/templates/agents/tdd-orchestrator.agent.md +183 -0
  72. package/templates/agents/temporal-python-pro.agent.md +349 -0
  73. package/templates/agents/terraform-specialist.agent.md +137 -0
  74. package/templates/agents/test-automator.agent.md +203 -0
  75. package/templates/agents/threat-modeling-expert.agent.md +44 -0
  76. package/templates/agents/tutorial-engineer.agent.md +118 -0
  77. package/templates/agents/ui-ux-designer.agent.md +188 -0
  78. package/templates/agents/ui-visual-validator.agent.md +192 -0
  79. package/templates/agents/vector-database-engineer.agent.md +43 -0
  80. package/templates/skills/angular-migration/SKILL.md +410 -0
  81. package/templates/skills/api-design-principles/SKILL.md +528 -0
  82. package/templates/skills/api-design-principles/assets/api-design-checklist.md +155 -0
  83. package/templates/skills/api-design-principles/assets/rest-api-template.py +182 -0
  84. package/templates/skills/api-design-principles/references/graphql-schema-design.md +583 -0
  85. package/templates/skills/api-design-principles/references/rest-best-practices.md +408 -0
  86. package/templates/skills/architecture-decision-records/SKILL.md +428 -0
  87. package/templates/skills/architecture-patterns/SKILL.md +494 -0
  88. package/templates/skills/async-python-patterns/SKILL.md +694 -0
  89. package/templates/skills/auth-implementation-patterns/SKILL.md +634 -0
  90. package/templates/skills/changelog-automation/SKILL.md +552 -0
  91. package/templates/skills/code-review-excellence/SKILL.md +520 -0
  92. package/templates/skills/competitive-landscape/SKILL.md +479 -0
  93. package/templates/skills/context-driven-development/SKILL.md +385 -0
  94. package/templates/skills/cost-optimization/SKILL.md +274 -0
  95. package/templates/skills/cqrs-implementation/SKILL.md +554 -0
  96. package/templates/skills/data-quality-frameworks/SKILL.md +587 -0
  97. package/templates/skills/data-storytelling/SKILL.md +453 -0
  98. package/templates/skills/database-migration/SKILL.md +424 -0
  99. package/templates/skills/dbt-transformation-patterns/SKILL.md +561 -0
  100. package/templates/skills/debugging-strategies/SKILL.md +527 -0
  101. package/templates/skills/defi-protocol-templates/SKILL.md +454 -0
  102. package/templates/skills/dependency-upgrade/SKILL.md +409 -0
  103. package/templates/skills/deployment-pipeline-design/SKILL.md +359 -0
  104. package/templates/skills/distributed-tracing/SKILL.md +438 -0
  105. package/templates/skills/dotnet-backend-patterns/SKILL.md +815 -0
  106. package/templates/skills/dotnet-backend-patterns/assets/repository-template.cs +523 -0
  107. package/templates/skills/dotnet-backend-patterns/assets/service-template.cs +336 -0
  108. package/templates/skills/dotnet-backend-patterns/references/dapper-patterns.md +544 -0
  109. package/templates/skills/dotnet-backend-patterns/references/ef-core-best-practices.md +355 -0
  110. package/templates/skills/e2e-testing-patterns/SKILL.md +547 -0
  111. package/templates/skills/employment-contract-templates/SKILL.md +507 -0
  112. package/templates/skills/error-handling-patterns/SKILL.md +636 -0
  113. package/templates/skills/event-store-design/SKILL.md +437 -0
  114. package/templates/skills/fastapi-templates/SKILL.md +567 -0
  115. package/templates/skills/git-advanced-workflows/SKILL.md +400 -0
  116. package/templates/skills/github-actions-templates/SKILL.md +333 -0
  117. package/templates/skills/go-concurrency-patterns/SKILL.md +655 -0
  118. package/templates/skills/grafana-dashboards/SKILL.md +369 -0
  119. package/templates/skills/helm-chart-scaffolding/SKILL.md +544 -0
  120. package/templates/skills/helm-chart-scaffolding/assets/Chart.yaml.template +42 -0
  121. package/templates/skills/helm-chart-scaffolding/assets/values.yaml.template +185 -0
  122. package/templates/skills/helm-chart-scaffolding/references/chart-structure.md +500 -0
  123. package/templates/skills/helm-chart-scaffolding/scripts/validate-chart.sh +244 -0
  124. package/templates/skills/javascript-testing-patterns/SKILL.md +1025 -0
  125. package/templates/skills/langchain-architecture/SKILL.md +338 -0
  126. package/templates/skills/llm-evaluation/SKILL.md +471 -0
  127. package/templates/skills/microservices-patterns/SKILL.md +595 -0
  128. package/templates/skills/modern-javascript-patterns/SKILL.md +911 -0
  129. package/templates/skills/monorepo-management/SKILL.md +622 -0
  130. package/templates/skills/nextjs-app-router-patterns/SKILL.md +544 -0
  131. package/templates/skills/nodejs-backend-patterns/SKILL.md +1020 -0
  132. package/templates/skills/nx-workspace-patterns/SKILL.md +452 -0
  133. package/templates/skills/openapi-spec-generation/SKILL.md +1028 -0
  134. package/templates/skills/paypal-integration/SKILL.md +467 -0
  135. package/templates/skills/pci-compliance/SKILL.md +466 -0
  136. package/templates/skills/postgresql/SKILL.md +204 -0
  137. package/templates/skills/projection-patterns/SKILL.md +490 -0
  138. package/templates/skills/prometheus-configuration/SKILL.md +392 -0
  139. package/templates/skills/prompt-engineering-patterns/SKILL.md +201 -0
  140. package/templates/skills/prompt-engineering-patterns/assets/few-shot-examples.json +106 -0
  141. package/templates/skills/prompt-engineering-patterns/assets/prompt-template-library.md +246 -0
  142. package/templates/skills/prompt-engineering-patterns/references/chain-of-thought.md +399 -0
  143. package/templates/skills/prompt-engineering-patterns/references/few-shot-learning.md +369 -0
  144. package/templates/skills/prompt-engineering-patterns/references/prompt-optimization.md +414 -0
  145. package/templates/skills/prompt-engineering-patterns/references/prompt-templates.md +470 -0
  146. package/templates/skills/prompt-engineering-patterns/references/system-prompts.md +189 -0
  147. package/templates/skills/prompt-engineering-patterns/scripts/optimize-prompt.py +279 -0
  148. package/templates/skills/python-packaging/SKILL.md +870 -0
  149. package/templates/skills/python-performance-optimization/SKILL.md +869 -0
  150. package/templates/skills/python-testing-patterns/SKILL.md +907 -0
  151. package/templates/skills/rag-implementation/SKILL.md +403 -0
  152. package/templates/skills/react-modernization/SKILL.md +513 -0
  153. package/templates/skills/react-native-architecture/SKILL.md +671 -0
  154. package/templates/skills/react-state-management/SKILL.md +429 -0
  155. package/templates/skills/risk-metrics-calculation/SKILL.md +555 -0
  156. package/templates/skills/rust-async-patterns/SKILL.md +517 -0
  157. package/templates/skills/secrets-management/SKILL.md +346 -0
  158. package/templates/skills/security-requirement-extraction/SKILL.md +677 -0
  159. package/templates/skills/shellcheck-configuration/SKILL.md +454 -0
  160. package/templates/skills/similarity-search-patterns/SKILL.md +558 -0
  161. package/templates/skills/slo-implementation/SKILL.md +329 -0
  162. package/templates/skills/sql-optimization-patterns/SKILL.md +493 -0
  163. package/templates/skills/stripe-integration/SKILL.md +442 -0
  164. package/templates/skills/tailwind-design-system/SKILL.md +666 -0
  165. package/templates/skills/temporal-python-testing/SKILL.md +158 -0
  166. package/templates/skills/temporal-python-testing/resources/integration-testing.md +455 -0
  167. package/templates/skills/temporal-python-testing/resources/local-setup.md +553 -0
  168. package/templates/skills/temporal-python-testing/resources/replay-testing.md +462 -0
  169. package/templates/skills/temporal-python-testing/resources/unit-testing.md +328 -0
  170. package/templates/skills/terraform-module-library/SKILL.md +249 -0
  171. package/templates/skills/terraform-module-library/references/aws-modules.md +63 -0
  172. package/templates/skills/threat-mitigation-mapping/SKILL.md +745 -0
  173. package/templates/skills/track-management/SKILL.md +593 -0
  174. package/templates/skills/typescript-advanced-types/SKILL.md +717 -0
  175. package/templates/skills/uv-package-manager/SKILL.md +831 -0
  176. package/templates/skills/vector-index-tuning/SKILL.md +521 -0
  177. package/templates/skills/wcag-audit-patterns/SKILL.md +555 -0
  178. package/templates/skills/workflow-orchestration-patterns/SKILL.md +316 -0
  179. package/templates/skills/workflow-patterns/SKILL.md +623 -0
  180. package/templates/agents/game-developer.agent.md +0 -57
  181. package/templates/agents/kubernetes-specialist.agent.md +0 -56
  182. package/templates/agents/market-researcher.agent.md +0 -47
@@ -0,0 +1,493 @@
1
+ ---
2
+ name: sql-optimization-patterns
3
+ 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.
4
+ ---
5
+
6
+ # SQL Optimization Patterns
7
+
8
+ Transform 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
+
25
+ Understanding EXPLAIN output is fundamental to optimization.
26
+
27
+ **PostgreSQL EXPLAIN:**
28
+ ```sql
29
+ -- Basic explain
30
+ EXPLAIN SELECT * FROM users WHERE email = 'user@example.com';
31
+
32
+ -- With actual execution stats
33
+ EXPLAIN ANALYZE
34
+ SELECT * FROM users WHERE email = 'user@example.com';
35
+
36
+ -- Verbose output with more details
37
+ EXPLAIN (ANALYZE, BUFFERS, VERBOSE)
38
+ SELECT u.*, o.order_total
39
+ FROM users u
40
+ JOIN orders o ON u.id = o.user_id
41
+ WHERE u.created_at > NOW() - INTERVAL '30 days';
42
+ ```
43
+
44
+ **Key Metrics to Watch:**
45
+ - **Seq Scan**: Full table scan (usually slow for large tables)
46
+ - **Index Scan**: Using index (good)
47
+ - **Index Only Scan**: Using index without touching table (best)
48
+ - **Nested Loop**: Join method (okay for small datasets)
49
+ - **Hash Join**: Join method (good for larger datasets)
50
+ - **Merge Join**: Join method (good for sorted data)
51
+ - **Cost**: Estimated query cost (lower is better)
52
+ - **Rows**: Estimated rows returned
53
+ - **Actual Time**: Real execution time
54
+
55
+ ### 2. Index Strategies
56
+
57
+ Indexes are the most powerful optimization tool.
58
+
59
+ **Index Types:**
60
+ - **B-Tree**: Default, good for equality and range queries
61
+ - **Hash**: Only for equality (=) comparisons
62
+ - **GIN**: Full-text search, array queries, JSONB
63
+ - **GiST**: Geometric data, full-text search
64
+ - **BRIN**: Block Range INdex for very large tables with correlation
65
+
66
+ ```sql
67
+ -- Standard B-Tree index
68
+ CREATE INDEX idx_users_email ON users(email);
69
+
70
+ -- Composite index (order matters!)
71
+ CREATE INDEX idx_orders_user_status ON orders(user_id, status);
72
+
73
+ -- Partial index (index subset of rows)
74
+ CREATE INDEX idx_active_users ON users(email)
75
+ WHERE status = 'active';
76
+
77
+ -- Expression index
78
+ CREATE INDEX idx_users_lower_email ON users(LOWER(email));
79
+
80
+ -- Covering index (include additional columns)
81
+ CREATE INDEX idx_users_email_covering ON users(email)
82
+ INCLUDE (name, created_at);
83
+
84
+ -- Full-text search index
85
+ CREATE INDEX idx_posts_search ON posts
86
+ USING GIN(to_tsvector('english', title || ' ' || body));
87
+
88
+ -- JSONB index
89
+ CREATE INDEX idx_metadata ON events USING GIN(metadata);
90
+ ```
91
+
92
+ ### 3. Query Optimization Patterns
93
+
94
+ **Avoid SELECT \*:**
95
+ ```sql
96
+ -- Bad: Fetches unnecessary columns
97
+ SELECT * FROM users WHERE id = 123;
98
+
99
+ -- Good: Fetch only what you need
100
+ SELECT id, email, name FROM users WHERE id = 123;
101
+ ```
102
+
103
+ **Use WHERE Clause Efficiently:**
104
+ ```sql
105
+ -- Bad: Function prevents index usage
106
+ SELECT * FROM users WHERE LOWER(email) = 'user@example.com';
107
+
108
+ -- Good: Create functional index or use exact match
109
+ CREATE INDEX idx_users_email_lower ON users(LOWER(email));
110
+ -- Then:
111
+ SELECT * FROM users WHERE LOWER(email) = 'user@example.com';
112
+
113
+ -- Or store normalized data
114
+ SELECT * FROM users WHERE email = 'user@example.com';
115
+ ```
116
+
117
+ **Optimize JOINs:**
118
+ ```sql
119
+ -- Bad: Cartesian product then filter
120
+ SELECT u.name, o.total
121
+ FROM users u, orders o
122
+ WHERE u.id = o.user_id AND u.created_at > '2024-01-01';
123
+
124
+ -- Good: Filter before join
125
+ SELECT u.name, o.total
126
+ FROM users u
127
+ JOIN orders o ON u.id = o.user_id
128
+ WHERE u.created_at > '2024-01-01';
129
+
130
+ -- Better: Filter both tables
131
+ SELECT u.name, o.total
132
+ FROM (SELECT * FROM users WHERE created_at > '2024-01-01') u
133
+ JOIN orders o ON u.id = o.user_id;
134
+ ```
135
+
136
+ ## Optimization Patterns
137
+
138
+ ### Pattern 1: Eliminate N+1 Queries
139
+
140
+ **Problem: N+1 Query Anti-Pattern**
141
+ ```python
142
+ # Bad: Executes N+1 queries
143
+ users = db.query("SELECT * FROM users LIMIT 10")
144
+ for user in users:
145
+ orders = db.query("SELECT * FROM orders WHERE user_id = ?", user.id)
146
+ # Process orders
147
+ ```
148
+
149
+ **Solution: Use JOINs or Batch Loading**
150
+ ```sql
151
+ -- Solution 1: JOIN
152
+ SELECT
153
+ u.id, u.name,
154
+ o.id as order_id, o.total
155
+ FROM users u
156
+ LEFT JOIN orders o ON u.id = o.user_id
157
+ WHERE u.id IN (1, 2, 3, 4, 5);
158
+
159
+ -- Solution 2: Batch query
160
+ SELECT * FROM orders
161
+ WHERE user_id IN (1, 2, 3, 4, 5);
162
+ ```
163
+
164
+ ```python
165
+ # Good: Single query with JOIN or batch load
166
+ # Using JOIN
167
+ results = db.query("""
168
+ SELECT u.id, u.name, o.id as order_id, o.total
169
+ FROM users u
170
+ LEFT JOIN orders o ON u.id = o.user_id
171
+ WHERE u.id IN (1, 2, 3, 4, 5)
172
+ """)
173
+
174
+ # Or batch load
175
+ users = db.query("SELECT * FROM users LIMIT 10")
176
+ user_ids = [u.id for u in users]
177
+ orders = db.query(
178
+ "SELECT * FROM orders WHERE user_id IN (?)",
179
+ user_ids
180
+ )
181
+ # Group orders by user_id
182
+ orders_by_user = {}
183
+ for order in orders:
184
+ orders_by_user.setdefault(order.user_id, []).append(order)
185
+ ```
186
+
187
+ ### Pattern 2: Optimize Pagination
188
+
189
+ **Bad: OFFSET on Large Tables**
190
+ ```sql
191
+ -- Slow for large offsets
192
+ SELECT * FROM users
193
+ ORDER BY created_at DESC
194
+ LIMIT 20 OFFSET 100000; -- Very slow!
195
+ ```
196
+
197
+ **Good: Cursor-Based Pagination**
198
+ ```sql
199
+ -- Much faster: Use cursor (last seen ID)
200
+ SELECT * FROM users
201
+ WHERE created_at < '2024-01-15 10:30:00' -- Last cursor
202
+ ORDER BY created_at DESC
203
+ LIMIT 20;
204
+
205
+ -- With composite sorting
206
+ SELECT * FROM users
207
+ WHERE (created_at, id) < ('2024-01-15 10:30:00', 12345)
208
+ ORDER BY created_at DESC, id DESC
209
+ LIMIT 20;
210
+
211
+ -- Requires index
212
+ CREATE INDEX idx_users_cursor ON users(created_at DESC, id DESC);
213
+ ```
214
+
215
+ ### Pattern 3: Aggregate Efficiently
216
+
217
+ **Optimize COUNT Queries:**
218
+ ```sql
219
+ -- Bad: Counts all rows
220
+ SELECT COUNT(*) FROM orders; -- Slow on large tables
221
+
222
+ -- Good: Use estimates for approximate counts
223
+ SELECT reltuples::bigint AS estimate
224
+ FROM pg_class
225
+ WHERE relname = 'orders';
226
+
227
+ -- Good: Filter before counting
228
+ SELECT COUNT(*) FROM orders
229
+ WHERE created_at > NOW() - INTERVAL '7 days';
230
+
231
+ -- Better: Use index-only scan
232
+ CREATE INDEX idx_orders_created ON orders(created_at);
233
+ SELECT COUNT(*) FROM orders
234
+ WHERE created_at > NOW() - INTERVAL '7 days';
235
+ ```
236
+
237
+ **Optimize GROUP BY:**
238
+ ```sql
239
+ -- Bad: Group by then filter
240
+ SELECT user_id, COUNT(*) as order_count
241
+ FROM orders
242
+ GROUP BY user_id
243
+ HAVING COUNT(*) > 10;
244
+
245
+ -- Better: Filter first, then group (if possible)
246
+ SELECT user_id, COUNT(*) as order_count
247
+ FROM orders
248
+ WHERE status = 'completed'
249
+ GROUP BY user_id
250
+ HAVING COUNT(*) > 10;
251
+
252
+ -- Best: Use covering index
253
+ CREATE INDEX idx_orders_user_status ON orders(user_id, status);
254
+ ```
255
+
256
+ ### Pattern 4: Subquery Optimization
257
+
258
+ **Transform Correlated Subqueries:**
259
+ ```sql
260
+ -- Bad: Correlated subquery (runs for each row)
261
+ SELECT u.name, u.email,
262
+ (SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id) as order_count
263
+ FROM users u;
264
+
265
+ -- Good: JOIN with aggregation
266
+ SELECT u.name, u.email, COUNT(o.id) as order_count
267
+ FROM users u
268
+ LEFT JOIN orders o ON o.user_id = u.id
269
+ GROUP BY u.id, u.name, u.email;
270
+
271
+ -- Better: Use window functions
272
+ SELECT DISTINCT ON (u.id)
273
+ u.name, u.email,
274
+ COUNT(o.id) OVER (PARTITION BY u.id) as order_count
275
+ FROM users u
276
+ LEFT JOIN orders o ON o.user_id = u.id;
277
+ ```
278
+
279
+ **Use CTEs for Clarity:**
280
+ ```sql
281
+ -- Using Common Table Expressions
282
+ WITH recent_users AS (
283
+ SELECT id, name, email
284
+ FROM users
285
+ WHERE created_at > NOW() - INTERVAL '30 days'
286
+ ),
287
+ user_order_counts AS (
288
+ SELECT user_id, COUNT(*) as order_count
289
+ FROM orders
290
+ WHERE created_at > NOW() - INTERVAL '30 days'
291
+ GROUP BY user_id
292
+ )
293
+ SELECT ru.name, ru.email, COALESCE(uoc.order_count, 0) as orders
294
+ FROM recent_users ru
295
+ LEFT JOIN user_order_counts uoc ON ru.id = uoc.user_id;
296
+ ```
297
+
298
+ ### Pattern 5: Batch Operations
299
+
300
+ **Batch INSERT:**
301
+ ```sql
302
+ -- Bad: Multiple individual inserts
303
+ INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com');
304
+ INSERT INTO users (name, email) VALUES ('Bob', 'bob@example.com');
305
+ INSERT INTO users (name, email) VALUES ('Carol', 'carol@example.com');
306
+
307
+ -- Good: Batch insert
308
+ INSERT INTO users (name, email) VALUES
309
+ ('Alice', 'alice@example.com'),
310
+ ('Bob', 'bob@example.com'),
311
+ ('Carol', 'carol@example.com');
312
+
313
+ -- Better: Use COPY for bulk inserts (PostgreSQL)
314
+ COPY users (name, email) FROM '/tmp/users.csv' CSV HEADER;
315
+ ```
316
+
317
+ **Batch UPDATE:**
318
+ ```sql
319
+ -- Bad: Update in loop
320
+ UPDATE users SET status = 'active' WHERE id = 1;
321
+ UPDATE users SET status = 'active' WHERE id = 2;
322
+ -- ... repeat for many IDs
323
+
324
+ -- Good: Single UPDATE with IN clause
325
+ UPDATE users
326
+ SET status = 'active'
327
+ WHERE id IN (1, 2, 3, 4, 5, ...);
328
+
329
+ -- Better: Use temporary table for large batches
330
+ CREATE TEMP TABLE temp_user_updates (id INT, new_status VARCHAR);
331
+ INSERT INTO temp_user_updates VALUES (1, 'active'), (2, 'active'), ...;
332
+
333
+ UPDATE users u
334
+ SET status = t.new_status
335
+ FROM temp_user_updates t
336
+ WHERE u.id = t.id;
337
+ ```
338
+
339
+ ## Advanced Techniques
340
+
341
+ ### Materialized Views
342
+
343
+ Pre-compute expensive queries.
344
+
345
+ ```sql
346
+ -- Create materialized view
347
+ CREATE MATERIALIZED VIEW user_order_summary AS
348
+ SELECT
349
+ u.id,
350
+ u.name,
351
+ COUNT(o.id) as total_orders,
352
+ SUM(o.total) as total_spent,
353
+ MAX(o.created_at) as last_order_date
354
+ FROM users u
355
+ LEFT JOIN orders o ON u.id = o.user_id
356
+ GROUP BY u.id, u.name;
357
+
358
+ -- Add index to materialized view
359
+ CREATE INDEX idx_user_summary_spent ON user_order_summary(total_spent DESC);
360
+
361
+ -- Refresh materialized view
362
+ REFRESH MATERIALIZED VIEW user_order_summary;
363
+
364
+ -- Concurrent refresh (PostgreSQL)
365
+ REFRESH MATERIALIZED VIEW CONCURRENTLY user_order_summary;
366
+
367
+ -- Query materialized view (very fast)
368
+ SELECT * FROM user_order_summary
369
+ WHERE total_spent > 1000
370
+ ORDER BY total_spent DESC;
371
+ ```
372
+
373
+ ### Partitioning
374
+
375
+ Split large tables for better performance.
376
+
377
+ ```sql
378
+ -- Range partitioning by date (PostgreSQL)
379
+ CREATE TABLE orders (
380
+ id SERIAL,
381
+ user_id INT,
382
+ total DECIMAL,
383
+ created_at TIMESTAMP
384
+ ) PARTITION BY RANGE (created_at);
385
+
386
+ -- Create partitions
387
+ CREATE TABLE orders_2024_q1 PARTITION OF orders
388
+ FOR VALUES FROM ('2024-01-01') TO ('2024-04-01');
389
+
390
+ CREATE TABLE orders_2024_q2 PARTITION OF orders
391
+ FOR VALUES FROM ('2024-04-01') TO ('2024-07-01');
392
+
393
+ -- Queries automatically use appropriate partition
394
+ SELECT * FROM orders
395
+ WHERE created_at BETWEEN '2024-02-01' AND '2024-02-28';
396
+ -- Only scans orders_2024_q1 partition
397
+ ```
398
+
399
+ ### Query Hints and Optimization
400
+
401
+ ```sql
402
+ -- Force index usage (MySQL)
403
+ SELECT * FROM users
404
+ USE INDEX (idx_users_email)
405
+ WHERE email = 'user@example.com';
406
+
407
+ -- Parallel query (PostgreSQL)
408
+ SET max_parallel_workers_per_gather = 4;
409
+ SELECT * FROM large_table WHERE condition;
410
+
411
+ -- Join hints (PostgreSQL)
412
+ SET enable_nestloop = OFF; -- Force hash or merge join
413
+ ```
414
+
415
+ ## Best Practices
416
+
417
+ 1. **Index Selectively**: Too many indexes slow down writes
418
+ 2. **Monitor Query Performance**: Use slow query logs
419
+ 3. **Keep Statistics Updated**: Run ANALYZE regularly
420
+ 4. **Use Appropriate Data Types**: Smaller types = better performance
421
+ 5. **Normalize Thoughtfully**: Balance normalization vs performance
422
+ 6. **Cache Frequently Accessed Data**: Use application-level caching
423
+ 7. **Connection Pooling**: Reuse database connections
424
+ 8. **Regular Maintenance**: VACUUM, ANALYZE, rebuild indexes
425
+
426
+ ```sql
427
+ -- Update statistics
428
+ ANALYZE users;
429
+ ANALYZE VERBOSE orders;
430
+
431
+ -- Vacuum (PostgreSQL)
432
+ VACUUM ANALYZE users;
433
+ VACUUM FULL users; -- Reclaim space (locks table)
434
+
435
+ -- Reindex
436
+ REINDEX INDEX idx_users_email;
437
+ REINDEX TABLE users;
438
+ ```
439
+
440
+ ## Common Pitfalls
441
+
442
+ - **Over-Indexing**: Each index slows down INSERT/UPDATE/DELETE
443
+ - **Unused Indexes**: Waste space and slow writes
444
+ - **Missing Indexes**: Slow queries, full table scans
445
+ - **Implicit Type Conversion**: Prevents index usage
446
+ - **OR Conditions**: Can't use indexes efficiently
447
+ - **LIKE with Leading Wildcard**: `LIKE '%abc'` can't use index
448
+ - **Function in WHERE**: Prevents index usage unless functional index exists
449
+
450
+ ## Monitoring Queries
451
+
452
+ ```sql
453
+ -- Find slow queries (PostgreSQL)
454
+ SELECT query, calls, total_time, mean_time
455
+ FROM pg_stat_statements
456
+ ORDER BY mean_time DESC
457
+ LIMIT 10;
458
+
459
+ -- Find missing indexes (PostgreSQL)
460
+ SELECT
461
+ schemaname,
462
+ tablename,
463
+ seq_scan,
464
+ seq_tup_read,
465
+ idx_scan,
466
+ seq_tup_read / seq_scan AS avg_seq_tup_read
467
+ FROM pg_stat_user_tables
468
+ WHERE seq_scan > 0
469
+ ORDER BY seq_tup_read DESC
470
+ LIMIT 10;
471
+
472
+ -- Find unused indexes (PostgreSQL)
473
+ SELECT
474
+ schemaname,
475
+ tablename,
476
+ indexname,
477
+ idx_scan,
478
+ idx_tup_read,
479
+ idx_tup_fetch
480
+ FROM pg_stat_user_indexes
481
+ WHERE idx_scan = 0
482
+ ORDER BY pg_relation_size(indexrelid) DESC;
483
+ ```
484
+
485
+ ## Resources
486
+
487
+ - **references/postgres-optimization-guide.md**: PostgreSQL-specific optimization
488
+ - **references/mysql-optimization-guide.md**: MySQL/MariaDB optimization
489
+ - **references/query-plan-analysis.md**: Deep dive into EXPLAIN plans
490
+ - **assets/index-strategy-checklist.md**: When and how to create indexes
491
+ - **assets/query-optimization-checklist.md**: Step-by-step optimization guide
492
+ - **scripts/analyze-slow-queries.sql**: Identify slow queries in your database
493
+ - **scripts/index-recommendations.sql**: Generate index recommendations