Code tips · SQL · T-SQL
Why is this query slow? A practical SQL optimisation checklist
A monthly report query that joins a large payments table should not take minutes. Work through the four checks that fix most slow SQL queries: read the actual execution plan, make predicates sargable, index for the query you run, and fix stale statistics.
Every data team has one: the monthly report query that used to run in seconds and now takes minutes, usually discovered five minutes before the report is due. This article works through a realistic example — a district-level payments report for a social programme — and the four checks that fix most slow queries, in the order to try them.
The two tables:
| Column | Meaning |
|---|---|
payment_id |
Payment identifier (in dbo.beneficiary_payments) |
beneficiary_id |
Who was paid; joins to dbo.beneficiaries |
programme_id |
Which programme the payment belongs to |
payment_date |
When the payment was made |
amount |
Payment value |
status |
PAID, PENDING, FAILED |
district |
Beneficiary's district (in dbo.beneficiaries) |
And the slow report: total paid per district in 2026.
SELECT b.district,
SUM(p.amount) AS total_paid,
COUNT(*) AS payments
FROM dbo.beneficiary_payments AS p
JOIN dbo.beneficiaries AS b
ON b.beneficiary_id = p.beneficiary_id
WHERE YEAR(p.payment_date) = 2026
AND p.status = 'PAID'
GROUP BY b.district;
Check 1: Measure before you change anything
Optimisation without measurement is guessing. Turn on the two diagnostics that tell you where the time and reads actually go, and capture the actual execution plan, not the estimated one:
SET STATISTICS IO ON;
SET STATISTICS TIME ON;
-- Run the query with "Include Actual Execution Plan" (Ctrl+M in SSMS)
Read the plan from right to left and look for three things: a scan of the biggest table (the engine read every row), a key lookup repeated for a large number of rows (the engine found rows via an index, then fetched each one from the table), and any operator where the estimated row count is far from the actual count — that gap is the optimiser working from wrong information, and it points straight at Check 4. Note the baseline numbers (logical reads, elapsed time) so every change afterwards is proven, not hoped for. On a production system, Query Store does this continuously and keeps the history for you.
Check 2: Make the predicate sargable
Look at the filter: YEAR(p.payment_date) = 2026. Wrapping the column in a function forces the engine to evaluate the function for every row before it can filter — no index on payment_date can be used to seek, so the table gets scanned. The fix is to write the same condition as a range on the bare column, which an index can seek directly:
WHERE p.payment_date >= '2026-01-01'
AND p.payment_date < '2027-01-01'
AND p.status = 'PAID'
This pattern — a search-argument-able, or sargable, predicate — is the single most common slow-query fix. The same trap appears as CAST(date_column AS date), LEFT(code, 3) = 'ABC', or a join between columns of different data types, which makes the engine convert one side row by row. Keep functions and conversions on the value side of the comparison, never on the column side.
Check 3: Index for the query you actually run
With a sargable filter, an index can finally help. The query filters on programme_id and payment_date in other reports, joins on beneficiary_id, and reads amount and status. One composite index can serve it end to end — the key columns drive the seek, and INCLUDE carries the extra columns the query reads, so the engine never goes back to the table:
CREATE NONCLUSTERED INDEX IX_payments_programme_date
ON dbo.beneficiary_payments (programme_id, payment_date)
INCLUDE (beneficiary_id, amount, status);
An index like this is called covering: everything the query needs is in the index, and the key lookups from Check 1 disappear. Two cautions. Order matters — put equality-filtered columns first, then the range column. And every index is paid for on every insert and update, so index for the queries you run every day, not for every query anyone might run once.
Check 4: Fix the statistics before blaming the plan
If the plan's estimated rows say 1 and the actual rows say 1,000,000, the optimiser chose its join strategy — nested loops, merge or hash — using fiction. The usual cause is stale statistics: the optimiser's histograms no longer match the data, typically after a large load. Refresh them and compare the plan again:
UPDATE STATISTICS dbo.beneficiary_payments;
Statistics normally update automatically, but the automatic threshold is proportionally high on very large tables, so a fact table can absorb millions of new rows before its statistics move. If one query keeps picking a bad plan while its data grows, scheduled statistics maintenance — or a targeted update after each big load — is the boring fix that works. Only after statistics are right does it make sense to debate join types: hash joins for large unsorted inputs, merge joins when both sides are already sorted on the join key.
The checklist, in order
- Measure. Actual execution plan plus
STATISTICS IO/TIME; record the baseline. - Filter sargably. No functions on filtered or joined columns; ranges instead of
YEAR()/CAST(). - Index deliberately. Composite, covering indexes for the recurring queries; equality columns first.
- Refresh statistics. Especially after large loads; re-check the plan's estimates against actuals.
- Ask for less. No
SELECT *(it defeats covering indexes), aggregate the smallest set you can, and pre-aggregate a huge fact table when the question is at a coarser grain.
The same logic travels: in Microsoft Fabric's Warehouse and SQL analytics endpoint, and in Spark SQL, you are still managing scans, join strategies and stale metadata — plus data skew on join keys. If your team's reporting queries crawl and nobody owns the tuning, this is exactly the kind of work I do with programme and data teams — see what I offer, and for the query-writing side of SQL, the companion piece on window-function patterns.
Sources
- Display an actual execution plan — Microsoft Learn
- Create indexes with included columns — Microsoft Learn
- Statistics — Microsoft Learn
- Monitor performance by using the Query Store — Microsoft Learn