Blog Post

Common Mistakes in SQL Server – Part 6

,

Last week in our discussion on Common Mistakes in SQL Server – Part 5 we have discussed that Implicit conversions can indeed lead to suboptimal query performance, so addressing this issue is crucial for optimizing your database operations. Continuing the discussion on Common Mistakes in SQL Server – Part 6 this week I am focusing on discussing importance of recompile.

the advantages of recompiling stored procedures and views in SQL Server and underlined the scenarios where recompilation is recommended. Let’s summarize the key points:

  1. Caching Execution Plans: Views and stored procedures in SQL Server can store their execution plans in the system table sys.syscacheobjects, which is used to optimize subsequent executions of the same T-SQL statements.
  2. Execution Plan: An execution plan is a data structure that specifies how a query will be executed, optimizing the query for performance. It’s generated by the SQL Server engine for each unique query and stored in the cache.
  3. Reusing Cached Plans: SQL Server tries to reuse cached execution plans for views and stored procedures. This minimizes the overhead of repeatedly compiling the same T-SQL statements.

When to Recompile: There are specific events that can invalidate the cached execution plan, and recompilation is recommended in these cases. These events include:

  • Schema Changes: Altering a table’s structure.
  • Index Changes: Altering or dropping indexes.
  • Manual Recompile: Using sp_recompile, the ‘with recompile’ option, or OPTION (RECOMPILE) in your T-SQL.
  • Data Changes: Large insertions or deletions of data in tables.
  • Mixed DML and DDL: Combining Data Manipulation Language (DML) and Data Definition Language (DDL) in a single T-SQL statement.
  • SET Option Changes: Modifying the value of SET options can affect the query’s execution plan.

Cost of Recompilation: Recompilation is an expensive operation, as it involves generating a new execution plan. However, it helps ensure that the query uses an up-to-date and valid plan, which can improve performance and accuracy.

In summary, recompilation is a valuable tool in SQL Server when you want to ensure that your queries are using the most appropriate execution plans. It’s important to be aware of the events that can trigger recompilation and to use it judiciously to balance the performance benefits with the associated overhead. Addressing high CPU utilization is essential for maintaining the performance and stability of a SQL Server instance. If you encounter such issues please refer to this article Resolving High CPU usage in SQL Server.

Original post (opens in new tab)
View comments in original post (opens in new tab)

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating