Thursday, January 28, 2010

Difference between compilation and recompilation

While understanding the execution t-sql statements in SQL Server we usually encounter two words compilation and recompilation. Here I will through some light on the difference between these two:
Compilation: When a t-sql statement is executed first time its not like that it process data directly. The statement is passed through 4 steps: parsing > optimizing > compiling > execution. These steps are performed for each T-SQL query no matter how it is executed. Whether it is a ad hoc query or prepared statement or in a stored procedure, trigger, function, etc.
 Parsing: check the syntax and validity of statement and existence of underlying objects.
Optimizing: In this step SQL Engine evaluate many best possible execution methods to execute a query. As SQL Server uses the cost based approach so on the basis of data statistics and resource availability choose the best execution method to execute the query among many candidate plans. This is a heavy and processor intensive process.
Compiling: The best plan decided in optimization step is compiled and a compiled plan, also called query plan is generated. Compiled plan is shared by all users and no user context information and parameter values are stored in compiled plan.
Execution: At the time of execution a copy of compiled plan with user context information and actual parameter values is sent to processor. This copy is called execution plan. Execution plan can not be shared by multiple users and can be reused only if a user executes the same query again.
clip_image002
Recompilation: If the above explained 4 step process is performed even a compiled plan already exists in memory then this process is called recompilation. In other words SQL Server must be in the middle of executing a previously compiled plan when the decision is made to create the plan again. If the decision to generate a new plan is made prior to the start of query execution, that is considered a compile, not a recompile.
To track compilation and recompilation performance monitor provides two different counters in SQL Server: SQL Statistics object. These counters are: SQL Compilations/sec and SQL Re-Compilations/sec.

1 comment:

Anonymous said...

You really make it seem so easy with your presentation but I find this matter to be actually something which I think I would never
understand. It seems too complicated and extremely broad for me.

I am looking forward for your next post, I'll try to get the hang of it!


my webpage; the elder scrolls online guide how to reach level 50 in 7 days