Sql-server – Why do the outdated statistics degrade a query performance

sql server

Some facts:

1. The outdated statistics cause generating an inaccurate estimated
plan. The estimated execution plan is created by Query Optimizer
which uses both statistics and the query processor tree.

2. The actual execution plan is created after executing the query. When the stats are stale, the Storage Engine generates its own plan which is different than the estimated one.

The question: Why to bother about outdated stats if SQL Server can create accurate actual execution plan (by Storage Engine) when it finds out that data has been changed? How can the difference between the estimated and actual plan influences the query performance?

Best Answer

It seems that the facts you presented are not so precise, let me say:

1. The estimated execution plan is created by Query Optimizer which uses statistics to generate the query processor tree. (query processor tree = execution plan)

2. The actual execution plan is the estimated execution plan, annotated with the real cost. This can be used to validade how wrong is the plan.

If your query optimizer don't have good stats, it will generate bad plans. Your query will run with that bad plan and only at the end (after the execution), if you compare with the actual execution plan, it only proves that Query Optimizer estimated it all wrong. (i.e.: estimates 1 seek, executed 239827492 seeks)

What is called execution plan is the optimized version of the original parsed query tree. The process involved on the optimization is complex and it is a NP-complete problem. The changes made on the original tree are called optimization and they are done based on the statistics, as well as other variables such as number of CPUs available, etc. The plan does not changes during the execution, unless you consider Adaptive query processing, added on SQL Server 2017; but then this starts another topic

I would recommend that you check the following links understant better how it works:

SQL Server Statistics Basics - https://www.red-gate.com/simple-talk/sql/performance/sql-server-statistics-basics/

Execution Plan Basics - https://www.red-gate.com/simple-talk/sql/performance/execution-plan-basics/