Sql-server – Does Query Plan cache gets cleared by itself

optimizationplan-cacheplan-guidessql server

I have been working on query plan stored in plan cache and every time i search for a particular query with the below sql query,

SELECT cp.objtype AS ObjectType,
OBJECT_NAME(st.objectid,st.dbid) AS ObjectName,
cp.usecounts AS ExecutionCount,cp.plan_handle,
st.TEXT AS QueryText,
qp.query_plan AS QueryPlan
FROM sys.dm_exec_cached_plans AS cp
CROSS APPLY sys.dm_exec_query_plan(cp.plan_handle) AS qp
CROSS APPLY sys.dm_exec_sql_text(cp.plan_handle) AS st
where 
st.text like '%SearchModel%' 
order by ExecutionCount desc

I see different counts for the result.I am not clearing the plan cache and no other developers.
I am working on SQL Server 2016 and i have turned on Optimize for Adhoc option.The queries are generated from application using LINQ-SQL.So i hope the queries generated are adhoc.Please correct me if i am wrong.

Why is that the cached plan counts varies each time.?

Plan cache screenshot

Does anyone has any insight from the below screenshot regarding plan cache usage.It has more memory allocated for adhoch queries as queries in my application comes from LINQ-SQL.
I guess prepared queries are compiled queries?

Best Answer

It's very unlikely, but you could be experiencing the bug described in the first comment to this user voice item: Procedure Cache empties spontaneously even on an idle machine

This seems to happen when USERSTORE_TOKENPERM hits a certain value.
...
Under this configuration, the plan cache empties spontaneously when the USERSTORE_TOKENPERM size grows to around 5 GB

You can check for that with this query:

select pages_kb 
from sys.dm_os_memory_clerks 
where [type] = 'USERSTORE_TOKENPERM' and [name] = 'TokenAndPermUserStore';

There are several other factors that can cause your plan cache to be emptied. A non-exhaustive list of these factors includes:

  • someone ran the DBCC FREEPROCCACHE command to manually clear it
  • The server is under memory pressure, and old or single-use plans are being evicted from the cache