QueryOptimizer

When Does SQL Server Compile a New Query Plan?

2025-11-03 · 2 min

SQL Server is clever. It does not compile a new plan for every execution — it does so when compilation is needed. Before executing a query, the engine checks the plan cache. If a suitable cached plan exists, it may reuse it.

🔍 When is a new plan created?

Compilation or recompilation may occur when:

🧠 How can you inspect this?

1
2
3
4
5
6
7
8
9
-- podejrzyj, ile planów trzyma SQL Server
SELECT COUNT(*) AS PlansInCache FROM sys.dm_exec_cached_plans;

-- zobacz najczęściej używane plany
SELECT TOP 10 usecounts, objtype, cacheobjtype, size_in_bytes / 1024 AS KB,
       DB_NAME(st.dbid) AS DatabaseName, st.text
FROM sys.dm_exec_cached_plans cp
CROSS APPLY sys.dm_exec_sql_text(cp.plan_handle) st
ORDER BY usecounts DESC;

🧩 Why does it matter?

Frequent recompilation can consume unnecessary CPU. On the other hand, overly aggressive reuse can expose parameter sniffing problems. Balancing these behaviors is one of the keys to SQL Server performance.