الانتقال إلى المحتوى
قواعد البياناتQuery Tuning· 7 دقائق للقراءة

How to Read an Execution Plan Without Trusting the Cost Percentages

Cost percentages are the optimizer's predictions, even in an actual plan. Where the time went is in the actual rows, times and reads.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
محتويات المقال

A report query takes about 3 seconds. Its plan has two operators: a Clustered Index Scan at 95% of the cost and a Compute Scalar at 5%. So the team adds a covering index to get rid of the scan. In a test on SQL Server 2022, that index cut the plan's estimated cost from 10.4 to 0.14, and the query took 3.2 seconds. The 5% operator was calling a scalar function, and more than 90% of the elapsed time was spent inside it.

The common misconception

The belief: the percentage on each operator shows how much of the query's time that operator takes, so you fix the biggest one.

It's an easy belief to hold. The number is labelled "cost", it's the most visible number on the plan, and SQL Server Management Studio prints it on every operator of an actual plan too, which looks like a measurement. When every estimate is accurate and every step is costed, cost often does track the real work, so the habit gets rewarded often enough to stick.

What actually happens

Cost is a prediction, in the optimizer's own units

Both engines choose plans by estimated cost. Microsoft describes SQL Server's optimizer as cost-based: each candidate plan has a cost in computing resources, the optimizer picks one with a low estimated cost, and it relies on statistics to estimate it. PostgreSQL's docs are blunt about the units: costs are arbitrary, traditionally in units of disk page fetches, while EXPLAIN ANALYZE reports actual time in milliseconds, "so they are unlikely to match up". The cost also leaves things out; PostgreSQL's, for example, ignores the time to send rows to the client. A percentage is just one operator's share of that predicted total.

An actual plan doesn't replace the estimates

An actual plan adds runtime information to the compiled plan; it doesn't recompute the costs. In the plan XML from the test, each operator carried its EstimatedTotalSubtreeCost and, separately, measured counters: actual rows, executions, elapsed and CPU milliseconds, logical reads. The percentages come from the first set. The scan was 95% of the estimated cost; measured, it took between 80 and 210 ms of a query that ran 2.7 to 4.7 seconds across seven runs.

Some work isn't costed at all

Microsoft's page on scalar UDF inlining lists "lack of costing" among the reasons scalar functions perform poorly: the optimizer costs relational operators but not scalar ones, so an expensive function call can still look nearly free. In the test, the function ran a query per row, 35,202 times. Its queries don't appear in the outer plan, and SET STATISTICS IO listed only the 11,972 reads of the outer scan. The root operator's QueryTimeStats told the real story: UdfElapsedTime was 94% to 98% of ElapsedTime in every run.

Wrong estimates make wrong percentages

Every cost is built on a : how many rows the optimizer expects at each step. If it expects 1 row and gets 100,000, every cost on that branch was computed for the wrong amount of work, and so was every percentage. PostgreSQL's docs name the first thing to check: whether the estimated row counts are reasonably close to reality. A later article in this path covers where those estimates come from.

Number in the planWhat it really isUse it to
Cost % on an operatorShare of the optimizer's estimated total, in its own unitsSee what the optimizer believed
Estimated rowsA prediction from statisticsCompare with actual rows
Actual rows and executionsMeasured; in PostgreSQL, rows and time are per-loop averagesSpot bad estimates and repeated work
Actual elapsed and CPU timeMeasured per operatorFind where the time went
Logical reads, buffersMeasured pages touchedCompare the I/O of two versions

Measure, then compare versions

SQL
CREATE OR ALTER FUNCTION dbo.CustomerTier (@customerId int)RETURNS varchar(10) WITH INLINE = OFFASBEGIN    DECLARE @total decimal(18, 2) =        (SELECT SUM(Total) FROM dbo.Orders WHERE CustomerId = @customerId);    RETURN CASE WHEN @total > 5000 THEN 'Gold' ELSE 'Standard' END;END;GO-- Plan: scan 95% of the cost. Tested: ~95% of the time is in the UDFSELECT o.Id, o.Total, dbo.CustomerTier(o.CustomerId) AS TierFROM dbo.Orders AS oWHERE o.CreatedAt >= '2025-11-01';

The rewrite returned the same rows and ran about 20 times faster. Yet put both queries in one batch and their estimated costs, 10.4 and 12.5, make the rewrite 55% of the batch, as if it were the slower one. Comparing versions by "query cost relative to the batch" would have kept the 3-second query. WITH INLINE = OFF keeps the demo honest: SQL Server 2019 and later can inline many scalar functions, but not all of them.

To get the measured numbers, ask for them explicitly:

SQL
SET STATISTICS XML ON;      -- actual plan with runtime countersSET STATISTICS IO, TIME ON; -- reads per table, CPU and elapsed timeSELECT o.Id, o.Total, dbo.CustomerTier(o.CustomerId) AS TierFROM dbo.Orders AS oWHERE o.CreatedAt >= '2025-11-01';

How to apply it in your project

  1. Get the actual plan and the totalsRun the slow query with the actual plan on, plus SET STATISTICS IO, TIME ON in SQL Server or EXPLAIN (ANALYZE) in PostgreSQL 18, on realistic data.
  2. Start at the rootRead the total elapsed and CPU time first. In SQL Server, check QueryTimeStats for UDF time before looking at any operator.
  3. Walk the operators by measured time and rowsLook for the operators with the largest actual time and reads, and for estimated rows far from actual rows. Those gaps explain most bad plan choices.
  4. Compare versions by measurementsJudge a rewrite or an index by elapsed time and reads over several runs, never by its cost percentage or its share of the batch.

Key takeaways

  • Cost percentages are predicted shares in the optimizer's own units, and an actual plan still shows the predicted ones.
  • Work the optimizer doesn't cost, like a non-inlined scalar UDF, can take 95% of the time behind a 5% operator.
  • Every cost rests on row estimates; compare estimated rows with actual rows before trusting any percentage.
  • Find the time in actual elapsed and CPU time, executions or loops, and reads.
  • Compare query versions by measured time and reads: in the test, the faster rewrite had the higher estimated cost.

📚 المصادر

  1. Using EXPLAIN — PostgreSQL Documentation
  2. Execution Plan Overview — SQL Server, Microsoft Learn
  3. Display an Actual Execution Plan — SQL Server, Microsoft Learn
  4. Query Processing Architecture Guide — SQL Server, Microsoft Learn
  5. Scalar UDF Inlining — SQL Server, Microsoft Learn

التعليقات (0)