$npx -y skills add girijashankarj/cursor-handbook --skill query-optimizationWorkflow for identifying and fixing slow database queries. Use when a query is slow or the user asks to optimize database performance.
| 1 | # Skill: Optimize Database Query |
| 2 | |
| 3 | ## Trigger |
| 4 | When a query is slow or user asks to optimize database performance. |
| 5 | |
| 6 | ## Steps |
| 7 | |
| 8 | ### Step 1: Identify Slow Query |
| 9 | - [ ] Get the query text |
| 10 | - [ ] Measure current execution time |
| 11 | - [ ] Check query frequency (how often it runs) |
| 12 | |
| 13 | ### Step 2: Analyze Query Plan |
| 14 | - [ ] Run EXPLAIN ANALYZE on the query |
| 15 | - [ ] Identify sequential scans on large tables |
| 16 | - [ ] Check for missing indexes |
| 17 | - [ ] Look for unnecessary joins or subqueries |
| 18 | - [ ] Check sort operations (external sorts) |
| 19 | |
| 20 | ### Step 3: Optimize |
| 21 | Common optimizations: |
| 22 | - [ ] Add missing indexes |
| 23 | - [ ] Rewrite subqueries as JOINs |
| 24 | - [ ] Add WHERE clause filters to reduce data |
| 25 | - [ ] Use cursor-based pagination instead of OFFSET |
| 26 | - [ ] Add partial indexes for filtered queries |
| 27 | - [ ] Denormalize if read performance is critical |
| 28 | |
| 29 | ### Step 4: Benchmark |
| 30 | - [ ] Run optimized query with EXPLAIN ANALYZE |
| 31 | - [ ] Compare before/after execution times |
| 32 | - [ ] Test with production-like data volume |
| 33 | - [ ] Verify results are identical |
| 34 | |
| 35 | ### Step 5: Implement |
| 36 | - [ ] Update query in code |
| 37 | - [ ] Create migration for new indexes |
| 38 | - [ ] Add monitoring for the query |
| 39 | - [ ] Update any affected tests |
| 40 | |
| 41 | ## Completion |
| 42 | Query optimized with measurable improvement and monitoring in place. |