Data & Integrity

SQL Performance Tuning

Intermediate

The database is where most real performance problems live, and where a query that is instant on dev data becomes an outage on production volumes. Tuning SQL is a skill you can learn, and it is led by evidence: read the execution plan, index for your real queries, write sargable set-based SQL, and measure on realistic data. Guessing wastes effort. The plan tells you the truth.

We use Dapper over SQL Server, so the SQL we write is the SQL that runs. There is no ORM to blame or to save us. The good news is that database performance is one of the easiest areas to diagnose. SQL Server shows you exactly how it ran a query (the execution plan), where the time and rows went, and whether it used your indexes. Tuning is reading that, making a fix, and measuring again.

This goes deeper than the Gotchas: SQL and Database Design pages, and connects to Performance & Resource Use, Data Modelling & Persistence, and Caching. The recurring theme: a missing index, a non-sargable predicate, an N+1 pattern, or an unbounded query is usually behind a slow page. All of these can be found and fixed.

Diagnose before you tune

Apply the high-value fixes

Non-sargable, unindexed, SELECT * SELECT * FROM Customers
WHERE YEAR(CreatedUtc) = 2024 AND UPPER(Email) = @e;
-- no useful index; functions on the columns force a full scan

Functions wrapped around the columns stop any index being used, so SQL Server scans the whole table. This is fine on dev, but an outage on a large tenant. SELECT * also pulls back columns you do not need.

Sargable, indexed, explicit SELECT Id, Email, Status FROM Customers
WHERE TenantId=@t AND Email=@e
AND CreatedUtc >= @from AND CreatedUtc < @to;
-- index: (TenantId, Email) and/or (TenantId, CreatedUtc)

Predicates compare the columns directly, so indexes can seek. Only the needed columns are returned, and tenant scoping is both correct and indexed. This stays fast and flat as data grows.

Self-review checklist

Why it matters: The database is the most common source of production slowness and outages, and unlike many performance problems it is easy to diagnose. The execution plan removes the guesswork. Engineers who can read a plan and apply the few high-value fixes (indexing, sargable predicates, set-based and bounded queries) keep the platform fast as it grows. That is core to being genuinely good at this work.