📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Why can the estimated cost percentages in a SQL Server execution plan be misleading, even in an actual plan?

Why the cost percentages in SQL Server plans are always estimates, the cases where they lie badly (bad cardinality, scalar UDFs, remote calls, parallelism), and how to find the real hotspot.

Intermediate Theory Intermediate cardinality-estimation execution-plans performance query-tuning sql-server

🎯 Key points

  • Percentages are estimated even in actual plans
  • Built from row estimates, so wrong whenever estimates are wrong
  • Scalar UDFs, remote calls and multi-statement TVFs are costed far too low
  • Parallel plans divide CPU cost by DOP, distorting comparisons
  • Use actual rows, executions and per-operator actual time, CPU and reads
  • Confirm with SET STATISTICS IO, TIME or Query Store

⏱ 30-second answer

The cost percentages are the optimiser's estimated costs, even in an actual plan; they are never recalculated from run time. If an operator was estimated at 10 rows and processed a million, it still shows a tiny percentage. Some work is costed close to nothing: scalar UDFs run per row, remote/linked-server calls and multi-statement TVFs get fixed guesses. Parallel plans divide CPU cost by DOP, which can make a heavy branch look cheap. So I compare estimated vs actual rows and executions, read the per-operator actual elapsed time, CPU and logical reads in the actual plan, and confirm with SET STATISTICS IO, TIME.

🗣 Full answer (senior)

Why they mislead. The optimiser assigns each operator a cost from its cost model: estimated rows × row size × CPU and I/O constants. The plan's percentages are each operator's share of that estimated total. An actual plan adds runtime counters (actual rows, executions, elapsed time, CPU, reads) but does not recompute the costs. So:

  1. Wrong estimates, wrong percentages. A Key Lookup estimated at 1 execution that actually ran 400,000 times shows 2% while doing nearly all the work.
  2. Under-costed operations.
    • Scalar UDFs (before inlining) appear as a cheap Compute Scalar, but the function body runs once per row, serially, and its reads aren't in the plan at all. A UDF doing a lookup on 1 million rows is 1 million hidden queries.
    • Remote queries / linked servers get fixed guesses; the remote side's work is invisible.
    • Multi-statement TVFs get a fixed estimate (1 row before SQL Server 2014's CE, 100 after) unless interleaved execution (2017+) corrects it.
  3. Parallelism. In a parallel plan the CPU part of an operator's cost is divided by the estimated DOP, but I/O cost isn't, so parallel branches look cheaper relative to serial ones. Exchange operators (Repartition / Gather Streams) and skewed work across threads aren't reflected well.
  4. Cost is not time. Cost units are abstract. A plan costing 50 can run slower than one costing 500 on your hardware.

What I do instead.

  • Walk the plan looking for the biggest gap between estimated and actual rows, and high actual executions.
  • Use per-operator actual elapsed time, CPU and logical reads (in the operator properties of actual plans on modern SQL Server and SSMS).
  • SET STATISTICS IO, TIME ON for reads per table and CPU vs elapsed.
  • For UDFs, check sys.dm_exec_function_stats and whether scalar UDF inlining (compat 150+) applies.
  • For production queries, sys.dm_exec_query_plan_stats (last actual plan) and Query Store for CPU, duration and reads over time.

Example. An EF Core report took 40 s and the plan said 85% was a Clustered Index Scan. The scan's actual time was 300 ms. The real cost was a scalar UDF in a computed column, shown as a 0% Compute Scalar, that read another table for each of 600,000 rows. Rewriting it as a join cut the query to 1.2 s.

🔍 What the interviewer is checking

Checks that they know costs are always estimates and how to measure real work.

Green flags: says percentages are estimated even in actual plans; uses estimated vs actual rows and executions; knows UDFs, remote calls and TVFs hide work; mentions parallel costing; confirms with STATISTICS IO/TIME or Query Store.

Red flags: goes straight for the highest percentage; thinks cost is milliseconds; never mentions actual rows; unaware of per-operator runtime stats.

📚 Learn in depth

The cost model. Costs are in abstract units calibrated decades ago (roughly seconds on a 1990s reference machine). Each operator has I/O cost (pages, random vs sequential) and CPU cost (per row). Subtree cost is the sum of children plus self. The optimiser uses these only to compare alternatives during optimisation; they are not predictions of time.

Parallel costing. For parallel plans the CPU cost of operators in the parallel zone is divided by DOP (capped by the number of schedulers the optimiser assumes, often half the cores visible for costing); I/O cost is not reduced. cost threshold for parallelism compares against the serial plan's cost. This is why a parallel plan may be chosen with a lower total cost, and why its per-operator percentages don't line up with serial expectations.

Runtime counters. Since SQL Server 2016 SP1 (and 2014 SP2), actual plans include RunTimeCountersPerThread with ActualElapsedms, ActualCPUms, ActualLogicalReads and ActualPhysicalReads. In row mode, elapsed time is cumulative including children; in batch mode it is per operator — read carefully.

Scalar UDF inlining. At compat 150+, eligible scalar UDFs (no time-dependent functions, no table variables with side effects, and so on) are inlined into the calling query as relational expressions, so they are costed and parallelisable. sys.sql_modules.is_inlineable tells you which.

Lightweight profiling. LAST_QUERY_PLAN_STATS (database scoped config) lets sys.dm_exec_query_plan_stats return the last actual plan with low overhead.

💻 Code

SET STATISTICS IO, TIME ON;

SELECT o.OrderId, dbo.fn_CustomerTier(o.CustomerId) AS Tier  -- per-row UDF
FROM dbo.Orders AS o
WHERE o.CreatedAt >= '2026-11-01';

SET STATISTICS IO, TIME OFF;

-- Hidden UDF work
SELECT OBJECT_NAME(object_id) AS fn, execution_count,
       total_worker_time / 1000 AS cpu_ms, total_logical_reads
FROM sys.dm_exec_function_stats
WHERE database_id = DB_ID();

-- Can it be inlined (compat 150+)?
SELECT OBJECT_NAME(object_id) AS fn, is_inlineable
FROM sys.sql_modules
WHERE object_id = OBJECT_ID(N'dbo.fn_CustomerTier');

-- Last actual plan for a cached query (needs LAST_QUERY_PLAN_STATS = ON)
SELECT qps.query_plan
FROM sys.dm_exec_cached_plans AS cp
CROSS APPLY sys.dm_exec_query_plan_stats(cp.plan_handle) AS qps;

-- Rewrite: the UDF's lookup as a join
SELECT o.OrderId, c.Tier
FROM dbo.Orders AS o
JOIN dbo.CustomerTiers AS c ON c.CustomerId = o.CustomerId
WHERE o.CreatedAt >= '2026-11-01';

⚠ Common mistakes

  • Tuning the operator with the biggest percentage without checking actual rows or time.
  • Believing an actual plan shows actual costs.
  • Missing scalar UDFs because they appear as a cheap Compute Scalar.
  • Comparing cost numbers between a serial and a parallel plan as if they were durations.
  • Using query cost to compare two queries' speed instead of measuring CPU, duration and reads.
  • Ignoring the Executions count on the inner side of nested loops.

🏛 Senior insight: trade-offs

I treat the cost percentages as the optimiser's opinion, useful for understanding why it chose the plan, not where the time went. To find where the time went I need measurements: actual rows and executions per operator, actual time and reads, and Query Store over many executions. The biggest wins come from the places the optimiser was wrong — the estimate gaps — and from work it can't see, like UDFs and remote calls. In code review I flag scalar UDFs in SELECT lists and WHERE clauses for exactly this reason.

↩ Usually asked after

More in Query Performance

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me