Why is the cache plan duplicated?

Copper Contributor

We have 2 queries. Each has the same QueryHash and QueryPlanHash.
But in the sys.dm_exec_cached_plans table, a cache is formed to perform each of these two queries.
This is mistake?

In fact, memory is inefficiently consumed, the caches of other requests are "washed out", which degrades the performance of the DBMS.

Synthetic example to play:

use master
DBCC FreeProcCache
select COUNT(*) from sys.dm_exec_cached_plans
DECLARE @number INT, @txt nvarchar(1000), @myid binary(16), @myidStr varchar(34)
SET @number = 1000;
WHILE @number > 0
  SET @myid = CONVERT(binary(16), NEWID())
  SET @myidStr = sys.fn_varbintohexstr(@myid)
  SET @txt = 'declare @result varbinary(1)
              set @result = (select top 1 0 as fld from dbo.spt_values
              where 0x0 <> ' + @myidStr + ')'
  exec sp_executesql @txt
  SET @number = @number - 1
select COUNT(*) count, SUM(size_in_bytes/1024)/1024 size_in_mbytes from sys.dm_exec_cached_plans

When executed with the value "@number = 1" after executing 7 entries in the sys.dm_exec_cached_plans table.
When executed with the value "@number = 1000" after executing 1006 records (39 mb) in the sys.dm_exec_cached_plans table.
The text "Execution Plan XML" of these requests matches exactly, except for the @myidStr value.

2 Replies

Good day @Dmitriy4096 ,


Let's go point by point:


>> We have 2 queries. Each has the same QueryHash and QueryPlanHash. But in the sys.dm_exec_cached_plans table...This is mistake?

Hash function by definition is a function which maps Multiple-To_Single relations, which mean that for several input we can get the same output. This has nopthing with the cache plan which might be difference. Therefore, Yes this is Normal


Regarding the title: Why is the cache plan duplicated?

New EP might be created for many reason including even if you have small change in the query text like a blank space, or if (as mentioned above) you pass different parameter.


>> I did not understood what is the second question you have. In general the if you use parameters then during first execution the server built the execution plan (EP) which fit this parameter, and this EP might be used for other execution even if the parameter is different. I recommend to search more information on: sql server parameter sniffing


So the plan is QueryPlanHash SyS.dm_exec_cashed_plans table...Did I write that wrongh?