Cursor prompt
Optimize Database Queries
Identify N+1 queries, add missing indexes, rewrite slow queries, and add performance monitoring to an existing application.
Optimize the database queries in {{project_name}}. ## ORM: {{orm}} | Database: {{database}} ## Current pain points: {{pain_points}} ### Code to Audit: ```{{language}} {{code_to_review}} ``` ### Step 1: Identify Problems Scan for: - N+1 queries: a query inside a loop, or relations fetched without include/join - SELECT * queries fetching columns that are never used - Missing pagination — unbounded queries on large tables - No indexes on WHERE/ORDER BY/JOIN columns - Repeated identical queries in the same request (no request-level caching) - Queries inside transactions that could be batched ### Step 2: Fix Each Issue **N+1 Fix Patterns** - Prisma: add include: { relation: true } to the parent query - SQL: rewrite as JOIN or batch with WHERE id IN (array) - Multi-level N+1: use DataLoader-style batching **Index Additions** - Single column index for equality filters - Composite index for multi-column WHERE (order: equality first, then range) - Partial index for low-cardinality filtered queries (WHERE status = 'active') **Pagination** - Replace OFFSET with cursor: WHERE id > $cursor ORDER BY id LIMIT $n - Return nextCursor alongside results ### Step 3: Add Monitoring - Log queries exceeding 100ms with full query text and bind params - Add EXPLAIN ANALYZE to the 5 slowest identified queries ### Output Refactored code, index migration SQL, monitoring setup, and before/after query count comparison.
Fill in: {{project_name}}, {{orm}}, {{database}}, {{pain_points}}, {{language}}, {{code_to_review}}. In Loopy you fill these in a form and copy the finished prompt in one click.
More refactoring prompts
- CursorAdd TypeScript to Legacy JavaScriptIncrementally migrate a JavaScript codebase to TypeScript without breaking changes, starting with the most critical files.
- CursorRefactor with Zero RegressionsStructured refactoring prompt that ensures existing behavior is preserved while improving code quality.
- CopilotTranslate Code Between LanguagesConvert code from one programming language to another while preserving logic, idioms, and error handling.

