Actionable, technology-agnostic guidelines for writing, tuning, and maintaining high-performance SQL queries across modern relational engines.
Your application is lightning fast until it hits the database. Suddenly, those sub-second API responses stretch into multi-second timeouts. Your users start complaining, your infrastructure costs spike, and you're frantically adding more servers when the real problem is happening at the query level.
Database performance problems don't just slow down applications—they cascade through your entire development cycle. Developers spend hours debugging what appear to be application issues that are actually poorly optimized queries. Production incidents pile up because a single slow query can lock up your entire database. Your infrastructure bill climbs as you throw more hardware at problems that require surgical precision, not brute force.
The traditional approach of "add an index and hope" doesn't scale with modern applications handling millions of rows across complex relational structures. You need systematic query optimization that works across PostgreSQL, MySQL, SQL Server, and other ANSI-SQL engines.
These Cursor Rules implement battle-tested query optimization principles that eliminate the guesswork from database performance tuning. Instead of reactive firefighting, you get proactive optimization patterns that prevent performance issues before they reach production.
The rules enforce proven practices like pushing filters early, creating composite indexes in optimal order, and structuring queries for maximum optimizer effectiveness. They work across major database engines and integrate with modern AI-powered optimization features in SQL Server 2025 and cloud platforms.
10x Faster Complex Queries: By enforcing proper join order and filter placement, queries that previously took 30+ seconds complete in under 3 seconds. The rules ensure your WHERE clauses hit indexed columns and joins follow optimal patterns.
75% Reduction in Index Maintenance Overhead: The rules prevent index proliferation by establishing clear guidelines for when to create covering indexes versus composite indexes. Your DBA time shifts from emergency optimization to strategic performance planning.
Eliminate Query Plan Regression: Standardized query patterns ensure consistent execution plans across deployments. The rules enforce parameter usage and statistics maintenance that keep your optimized queries performing consistently.
Cut Database Costs by 40%: Better queries mean fewer resources consumed per operation. You'll reduce CPU usage, minimize I/O operations, and decrease memory pressure—directly translating to lower cloud database costs.
Instead of manually checking slow query logs and trying to remember optimization best practices, these rules automatically structure your queries for optimal performance. When you write a complex analytical query joining multiple tables, the rules ensure proper composite index ordering and filter placement:
-- Automatically structured for optimal performance
WITH filtered_orders AS (
SELECT o_id, o_customer_id, o_total
FROM orders
WHERE o_date >= '2024-01-01' AND o_date < '2024-02-01' -- Half-open range
AND o_status = 'completed' -- Equality filter first
)
SELECT
c_name, -- Explicit column selection
SUM(fo_total) as revenue
FROM customers c
INNER JOIN filtered_orders fo ON c_id = fo_customer_id -- Indexed join
GROUP BY c_name -- Matches index prefix
The rules catch performance killers during development instead of after deployment. When a developer accidentally writes WHERE LOWER(email) = '[email protected]', the rules flag the function usage on an indexed column and suggest storing a computed search column instead.
Your team works with PostgreSQL locally, MySQL in staging, and SQL Server in production. The rules ensure your optimization patterns work consistently across all three, with engine-specific optimizations automatically applied where beneficial.
Copy the provided rules into your .cursorrules file in your project root. The rules immediately activate for any SQL files or database interaction code.
Enable query analysis tools for your database engine:
PostgreSQL: Activate pg_stat_statements and set up automated analysis of queries exceeding 100ms.
SQL Server: Enable Query Store and configure AI feedback collection for automatic optimization suggestions.
MySQL: Set up EXPLAIN ANALYZE integration and configure performance schema for query tracking.
Run your existing queries through the optimization patterns and measure the improvements. The rules include specific metrics to track: logical reads, physical reads, elapsed time, and plan stability.
Configure alerts for database wait statistics and query performance degradation. The rules define specific thresholds: alert when average disk waits exceed 20ms or buffer cache hit ratio drops below 90%.
Week 1: Immediate query structure improvements. New queries automatically follow optimization patterns, preventing common performance problems before they reach production.
Month 1: 50% reduction in slow query incidents. Existing problematic queries get identified and optimized using the systematic approaches defined in the rules.
Quarter 1: Measurable infrastructure cost reduction as optimized queries consume fewer database resources. Development velocity increases as fewer performance issues interrupt feature development.
Ongoing: Your database performance becomes predictable and scalable. New features ship with confidence because query optimization is built into your development process, not bolted on afterward.
The rules transform database optimization from reactive crisis management into proactive performance engineering. Your queries perform consistently, your database costs stay predictable, and your development team focuses on building features instead of debugging performance problems.
Start optimizing your queries systematically. Your production database—and your on-call schedule—will thank you.
## Technology Stack Declaration
You are an expert in relational query optimization for:
- PostgreSQL ≥16
- MySQL / MariaDB ≥10.6
- Microsoft SQL Server 2025 & Azure SQL Database
- IBM i Db2
- Any ANSI-SQL compliant engine supporting execution-plan inspection
## Key Principles
- Minimize I/O first; CPU second. Every rule below serves this goal.
- Push filters (WHERE) and projections (SELECT) as early as possible.
- Never "guess": always validate changes with the actual execution plan and runtime statistics.
- Prefer declarative clarity over clever tricks—let the optimizer work for you.
- Tune for the 95 th percentile workload, not isolated samples.
## SQL Language-Specific Rules
- Columns
- Explicitly list required columns; avoid `SELECT *`.
- Alias columns consistently: `<table_short>_<column>` (e.g., `u_email`).
- Indexing
- Create composite indexes in the exact predicate order (equality → range → inclusion).
- Use covering indexes when 3 or fewer small columns satisfy a hot query.
- Review unused or overlapping indexes quarterly with `pg_stat_user_indexes`, `sys.dm_db_index_usage_stats`, etc.
- Joins
- Join on indexed, data-type compatible columns.
- Prefer `INNER JOIN` unless NULL-preserving logic is required.
- Cap join fan-out to 7 tables; break into CTEs otherwise.
- Filtering & Predicates
- Avoid functions on indexed columns (`WHERE LOWER(email) = 'x'`)—store computed search columns instead.
- For time filters use half-open ranges: `>= '2024-01-01' AND < '2024-02-01'`.
- Aggregation & Ordering
- Ensure `GROUP BY` and `ORDER BY` columns are left-most in an index or sort keys are small.
- Use window functions instead of correlated subqueries when possible.
- Query Structure
- Prefer CTEs for readability **only** when they do not materialize; mark as `WITH ... /* MATERIALIZED */` in PostgreSQL if needed.
- Avoid implicit joins (comma syntax).
## Error Handling and Validation
- Surface optimizer warnings (`OPTION (RECOMPILE, QUERYTRACEON 3604)` in SQL Server, `EXPLAIN (ANALYZE, VERBOSE, BUFFERS)` in PostgreSQL) during tuning.
- Catch runtime failures:
- SQL Server: wrap risky logic in `TRY...CATCH` and log `ERROR_NUMBER()` + `ERROR_MESSAGE()`.
- PostgreSQL: use `EXCEPTION WHEN others THEN RAISE NOTICE ...` inside PL/pgSQL.
- Use query hints ONLY as a last resort; document intent and expiration date in-line (`/* force-index:user_idx REMOVE AFTER Q3 */`).
## Framework-Specific Rules
### SQL Server 2025 & Azure SQL
- Turn on Intelligent Query Processing (`ALTER DATABASE SCOPED CONFIGURATION SET OPTIMIZE_FOR_AD_HOC_WORKLOADS = ON`).
- Leverage Query Store Hints for plan-shaping instead of index hints.
- Consume AI Feedback with `sys.dm_exec_query_feedback_*` views; set up an automated job to apply recommended indexes weekly.
### PostgreSQL
- Enable `pg_stat_statements` and track `total_time > 100 ms` queries.
- Use `ANALYZE` or `VACUUM ANALYZE` after ≥10 % table churn.
- Partition large fact tables (`≥50 M` rows) by time or hash to keep index B-trees shallow.
### MySQL / MariaDB
- Use `EXPLAIN ANALYZE` (MySQL 8 +). Reject any plan with `filesort` + `Using temporary` unless query <5 ms.
- Stick to InnoDB; ensure `innodb_buffer_pool_size` ≥70 % of RAM for OLTP workloads.
### IBM i Db2
- Use Visual Explain to verify predicates are SARGable.
- Schedule `RUNSTATS` to maintain catalog statistics nightly.
## Testing & Benchmarking
- Create deterministic load scripts (e.g., `pgbench`, `HammerDB`) that mirror production ratios (read/write, row width).
- Measure:
- logical reads
- physical reads
- elapsed time
- plan stability between deployments.
- Treat regression if any metric degrades by >5 %.
## Performance Monitoring Patterns
- Track wait stats continuously:
- CPU (`SOS_SCHEDULER_YIELD`, `CPU_BUSY`)
- I/O (`PAGEIOLATCH_%`, `io_wait`)
- Memory (`RESOURCE_SEMAPHORE`).
- Alert when:
- Avg disk waits >20 ms
- Buffer cache hit ratio <90 %
- Rotate slow query logs daily; parse with pt-query-digest or pgbadger.
## Maintenance & House-Keeping
- Rebuild or reorganize indexes when fragmentation >30 % (SQL Server) or `pg_stat_all_indexes.relfilsiz` grows >20 %.
- Remove duplicate / redundant indexes each release cycle.
- Keep statistics current: auto-update + manual `UPDATE STATISTICS` after large bulk loads.
## Security Considerations
- Always parameterize queries to prevent injection.
- Restrict `SHOW PLAN` permissions to performance-engineer roles only.
- Obfuscate literal values in captured plans (`SET QUERY_STORE_CAPTURE_PARAMETERIZATION = ALL`).
## Common Pitfalls Checklist
- [ ] `SELECT *` present
- [ ] Function on indexed column
- [ ] Missing predicate on partition key
- [ ] JOINs without ON condition (cartesian)
- [ ] FORCED plan hints without review date
- [ ] Out-of-date statistics
Follow this rulebook to produce deterministic, maintainable, and high-performance SQL across modern relational databases.