How to Find the Estimation Cost for a Query

In the processes of executing a query the database optimizer calculates an estimate at the cost to run the query. This cost is determined based on statistics. The statistics help the optimizer guess how much CPU and IO will be used when running the query. The database optimizer calls the calculated cost as the Estimated Cost of a query. This Estimated code is only an estimate of the execution cost, it is not the actual cost of the query. The database optimizer uses the Estimated Cost of a query to determine the appropriate plan to use to process the query. One of those executions options is whether or not the optimizer should pick a plan that goes parallel or not.

If you want to know the Estimated Cost of a query you can find it stored in the cached plan for a query. Here is an example of how to extract the Estimated Cost for execution plans stored in the procedure cache.

,PlanHandles AS (
    SELECT  plan_handle
            ,SUM(total_elapsed_time) AS total_elapsed_time
            ,SUM(execution_count) AS total_execution_count
    FROM  sys.dm_exec_query_stats
    GROUP  BY plan_handle
,Plans AS (
    SELECT  ph.plan_handle
      FROM  PlanHandles ph
         OUTER APPLY sys.dm_exec_query_plan(ph.plan_handle) qp
SELECT p.plan_handle
      ,q.n.value(N'(@EstimateRows)[1]', N'FLOAT') AS EstimatedRows 
      ,q.n.value(N'@EstimatedTotalSubtreeCost', N'float') AS EstimatedCost 
WHERE q.n.value(N'@NodeId', N'INT') = 0 
ORDER BY total_elapsed_time DESC;

# # #

» See All Articles by Columnist Gregory A. Larsen

Gregory Larsen
Gregory A. Larsen is a DBA at Washington State Department of Health (DOH). Greg is responsible for maintaining SQL Server and other database management software. Greg works with customers and developers to design and implement database changes, and solve database/application related problems. Greg builds homegrown solutions to simplify and streamline common database management tasks, such as capacity management.

Latest Articles