// SQL snippet

Find single-use ad-hoc plans wasting plan cache memory in SQL Server

Thousands of one-shot query plans eat plan cache memory. One query measures the damage; one setting fixes the cause.

Main statement
SQL Server

The task

Applications that build SQL by pasting values into the text send a different batch for every value, and SQL Server caches a separate plan for each. Simple parameterization rescues only trivial statements such as a single-table lookup by key; anything with a join, a subquery or an IN list stays literal. Plans with usecounts = 1 and objtype Adhoc are the result, and at scale they can hold gigabytes of plan cache and push out the plans that are actually reused.

The snippet

Written for SQL Server.

SQL Server
SELECT COUNT(*) AS single_use_plans,
       CAST(SUM(CAST(size_in_bytes AS BIGINT)) / 1048576.0 AS DECIMAL(12,1)) AS wasted_mb
FROM sys.dm_exec_cached_plans
WHERE objtype = 'Adhoc'
  AND usecounts = 1;

How it works

sys.dm_exec_cached_plans lists every cached plan; objtype Adhoc means a non-parameterized batch, and usecounts = 1 means it has run exactly once since being cached: compiled for one set of literal values and never reused. The cost counter is size_in_bytes summed over those plans. CAST to BIGINT keeps the sum from overflowing INT. The server-side mitigation is the optimize for ad hoc workloads option: the first execution of a batch caches only a small compiled plan stub, and the full plan is cached when the same text runs a second time, so one-shot plans cost a few hundred bytes instead of tens of kilobytes. Parameterized code (sp_executesql, parameters from the client driver) reuses plans with or without it.

Variations

Enable the ad-hoc workload optimization

EXEC sp_configure 'show advanced options', 1; RECONFIGURE;
EXEC sp_configure 'optimize for ad hoc workloads', 1; RECONFIGURE;

Sample the wasteful single-use plans

SELECT TOP 20
    usecounts, size_in_bytes / 1024 AS size_kb,
    LEFT(t.text, 120) AS sample_text
FROM sys.dm_exec_cached_plans cp
CROSS APPLY sys.dm_exec_sql_text(cp.plan_handle) t
WHERE cp.objtype = 'Adhoc' AND cp.usecounts = 1
ORDER BY cp.size_in_bytes DESC;

Questions that come up

The count is huge. Is enabling the option enough?

It limits the damage from now on, but plans already cached keep their full size until they are evicted. DBCC FREESYSTEMCACHE('SQL Plans') removes ad hoc and prepared plans immediately, at the cost of a burst of recompiles as they come back; most systems just let normal eviction catch up. ALTER DATABASE ... SET PARAMETERIZATION FORCED is a stronger option for one database: it parameterizes literals in most statements, which also changes which plans get reused, so test it first.

Why not just parameterize everything instead?

That is the real fix: parameters from the client driver, or sp_executesql, give one plan per statement shape and also close the SQL injection hole that literal concatenation opens. The server option is for when the application is not yours to change, or not yet.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.