I follow a measure-first process rather than guessing. 1. Find the slow queries - SQL Server Query Store (top resource-consuming queries and plan regressions), Extended Events, or sys.dm_exec_query_stats. - Application-side: Application Insights dependency tracking, MiniProfiler, or EF Core logging to see the generated SQL and query counts per request. 2. Read the actual execution plan - Look for table or index scans on large tables, expensive key lookups, sorts and hash spills to tempdb, large differences between estimated and actual rows (statistics problems), implicit conversions, and parallelism issues. - SET STATISTICS IO, TIME ON shows logical reads, which are a good measure of query cost. 3. Common fixes Indexing - Add or adjust indexes for WHERE, JOIN and ORDER BY columns; composite indexes with the right column order; INCLUDE columns to create covering indexes and remove key lookups. - Remove unused or duplicate indexes that slow down writes. Query rewriting - Select only needed columns (avoid SELECT *). - Make predicates sargable: WHERE OrderDate >= '2026-01-01' AND OrderDate < '2027-01-01' instead of WHERE YEAR(OrderDate) = 2026; avoid functions on indexed columns and leading-wildcard LIKE. - Match parameter data types to column types (VARCHAR vs NVARCHAR) to avoid implicit conversions. - Replace correlated subqueries or row-by-row cursors with set-based joins. - Use EXISTS instead of COUNT(*) > 0, and avoid unnecessary DISTINCT. - Paginate large results (keyset pagination for deep pages). Statistics and parameters - Keep statistics updated; investigate parameter sniffing (OPTION (RECOMPILE) or OPTIMIZE FOR in specific cases, or Query Store plan forcing). Application-level (EF Core) - Avoid N+1 queries (Include or projections), use AsNoTracking for reads, AsSplitQuery for multiple collection includes, and batch operations (ExecuteUpdate, ExecuteDelete). Design-level - Caching frequently read data, summary tables for reports, partitioning very large tables, and read replicas. 4. Verify - Compare logical reads, duration and CPU before and after with realistic data volumes, and monitor in production to make sure the improvement holds. Example: "A dashboard query took 8 seconds. The plan showed a scan of 40 million rows because of YEAR(OrderDate) in the WHERE clause. Rewriting it as a date range and adding a covering index on (CustomerId, OrderDate) INCLUDE (Total) reduced it to 60 ms."
Ravindra Wadile · · 0 likes