Covers the SQL Server plan cache: cache keys (text hash, SET options, database), object types (Adhoc, Prepared, Proc), simple and forced parameterisation, single-use plan bloat from concatenated SQL and variable parameter lengths, sp_executesql, optimize for ad hoc workloads and how to measure cache health.
SQL Server caches compiled plans keyed by the hash of the exact statement text plus plan-affecting SET options and the database. Change one literal or even whitespace and it's a different entry.
SQL built by string concatenation produces a new single-use plan per value: compile CPU, megabytes of cache memory and churn that evicts useful plans. The fix is sp_executesql with typed parameters (what EF Core and Dapper do), plus optimize for ad hoc workloads to store only a stub the first time. Trade-off: reuse saves CPU but means one plan for every value.
"The plan cache is part of SQL Server's memory where compiled plans live so the same statement doesn't have to be optimised again. The lookup key is a hash of the exact statement text, plus plan-affecting SET options and the database. So
WHERE CustomerId = 42andWHERE CustomerId = 43are two different statements and two different plans. Insys.dm_exec_cached_plansyou see them as objtypeAdhoc. Parameterised statements sent throughsp_executesql, which is what SqlClient does when you add parameters, arePrepared, and stored procedures areProc.SQL Server tries to help with simple parameterisation, but only for queries simple enough that any parameter value would get the same plan: single table, no joins, trivial plan territory. Everything else stays ad hoc. Forced parameterisation is a database setting that replaces almost all literals with parameters. It can rescue a vendor app that concatenates SQL, but it turns every query into a sniffing candidate, so I'd treat it as a targeted fix with Query Store watching.
The mistake I see is code that builds SQL strings, like
\"... WHERE Email = '\" + email + \"'\". Besides being a SQL injection hole, every distinct value compiles a new plan. On a busy API that's thousands of single-use plans an hour, each tens of kilobytes or more, burning CPU on compilation and pushing useful plans and data pages out of memory. A subtler version isAddWithValuewith strings: SqlClient sizes the parameter from the value, sonvarchar(5)andnvarchar(6)are different texts and different plans. I fix it with typed parameters with explicit lengths, and turn on optimize for ad hoc workloads so one-off statements only leave a small stub. Parameterise by default; reuse is cheap, compilation isn't."
| objtype | Comes from | Reuse |
|---|---|---|
| Adhoc | Literal SQL, EXEC(@sql) |
Only for identical text |
| Prepared | sp_executesql, auto-parameterised statements, client-prepared statements |
Across parameter values |
| Proc | Stored procedures, functions, triggers | Across parameter values |
| Option | What it does | Risk |
|---|---|---|
| Simple (default) | Auto-parameterises only safe, trivial queries | Most literal SQL still ad hoc |
Forced (ALTER DATABASE ... SET PARAMETERIZATION FORCED) |
Replaces most literals with parameters | More sniffing, can't see literals for filtered indexes |
Plan guide with PARAMETERIZATION FORCED template |
Forced for one query shape | Hard to discover and maintain |
sp_executesql in app code |
Explicit parameters | Sniffing (normal) |
A reporting service built filter SQL by concatenation. The plan cache held [about 45,000] Adhoc plans with usecounts = 1 using [3.8 GB], and compilations per second ran near batch requests per second. Switching to sp_executesql with typed parameters and enabling optimize for ad hoc workloads cut single-use plan memory to under 200 MB and CPU by about 25%.
Checks whether the candidate understands how plan reuse works and can connect application data-access code to SQL Server CPU and memory.
Green flags
AddWithValue length variance and concatenated SQL.sys.dm_exec_cached_plans and query_hash.Red flags
statement text --hash--> bucket
|
v
[cache entry: text + set_options + dbid + user_id(if unqualified)]
|
match? --yes--> execute (usecounts++)
|
no --> compile --> insert
Plan-affecting attributes include set_options (ARITHABORT, ANSI_NULLS, QUOTED_IDENTIFIER ...), the database, and the user id when object names aren't schema-qualified. That's why SELECT * FROM Orders from two users with different default schemas can get two plans; always write dbo.Orders.
SQL Server auto-parameterises a literal query only when it judges any value would produce the same plan. You see @1, @2 in the parameterised text. Joins, IN lists, subqueries, TOP, GROUP BY and many other constructs disqualify it. Even when it parameterises, the original Adhoc 'shell' plan is still cached as a pointer to the prepared one.
With PARAMETERIZATION FORCED, almost every literal in SELECT/INSERT/UPDATE/DELETE becomes a parameter (exceptions include literals in some clauses and statements with OPTION (RECOMPILE)). Good for an app you can't change; bad for queries that relied on literals to match filtered indexes or to get value-specific plans.
RESOURCE_SEMAPHORE_QUERY_COMPILE waits.optimize for ad hoc workloads (server option; database-scoped OPTIMIZE_FOR_AD_HOC_WORKLOADS in Azure SQL Database) stores only a compiled-plan stub (a few hundred bytes) on first execution and the full plan on the second.
cmd.Parameters.AddWithValue("@email", email); // nvarchar(len(email))
SqlClient infers nvarchar(n) from the value length when no size is set, so the statement text sent via sp_executesql differs (@email nvarchar(17) vs nvarchar(23)), giving one plan per length. EF Core avoids this by using the column's configured size or a fixed default. Set explicit types and sizes.
sys.dm_exec_cached_plans: count and size by objtype, usecounts = 1.sys.dm_exec_query_stats.query_hash: many plans with the same hash = same query shape not parameterised.sys.dm_os_performance_counters: SQL Compilations/sec vs Batch Requests/sec (a ratio above about 10% warrants a look).sys.dm_exec_cached_plans.sp_executesql and confirm one Prepared plan with usecounts = 100.AddWithValue with strings of different lengths from a small C# console app and count the plans.Compiled Plan Stub entries.sys.dm_exec_query_stats by query_hash and find shapes with more than 50 plans.Find single-use plan bloat and the query shapes causing it.
-- How much memory single-use ad hoc plans are using
SELECT objtype,
COUNT(*) AS plans,
SUM(CASE WHEN usecounts = 1 THEN 1 ELSE 0 END) AS single_use,
SUM(CAST(size_in_bytes AS bigint)) / 1048576 AS size_mb
FROM sys.dm_exec_cached_plans
GROUP BY objtype
ORDER BY size_mb DESC;
-- Same query shape, many plans: not parameterised
SELECT TOP (10) qs.query_hash, COUNT(*) AS plan_count, MIN(st.text) AS sample_text
FROM sys.dm_exec_query_stats qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) st
GROUP BY qs.query_hash
HAVING COUNT(*) > 50
ORDER BY plan_count DESC;
-- Store only a stub for first-time statements
EXEC sys.sp_configure 'show advanced options', 1; RECONFIGURE;
EXEC sys.sp_configure 'optimize for ad hoc workloads', 1; RECONFIGURE;
-- Azure SQL Database:
-- ALTER DATABASE SCOPED CONFIGURATION SET OPTIMIZE_FOR_AD_HOC_WORKLOADS = ON;
Before and after in C#: concatenation vs typed, fixed-length parameters.
namespace Shop.Data;
using System.Data;
using Microsoft.Data.SqlClient;
public sealed class CustomerLookup(string connectionString)
{
// Before: injection risk and one plan per email value
// var sql = $"SELECT CustomerId FROM dbo.Customers WHERE Email = '{email}'";
public async Task<int?> FindIdAsync(string email, CancellationToken ct)
{
await using var conn = new SqlConnection(connectionString);
await conn.OpenAsync(ct);
await using var cmd = new SqlCommand(
"SELECT CustomerId FROM dbo.Customers WHERE Email = @email", conn);
// varchar(256) matches the column: one plan, no implicit conversion
cmd.Parameters.Add("@email", SqlDbType.VarChar, 256).Value = email;
return (int?)await cmd.ExecuteScalarAsync(ct);
}
}
sp_executesql, Dapper, EF Core).AddWithValue for strings. Why it is wrong: Parameter length varies with the value (separate plans) and the type is nvarchar (implicit conversions on varchar columns). Instead: Parameters.Add(name, SqlDbType.VarChar, size).EXEC(@sql) for dynamic SQL. Why it is wrong: It can't take parameters, so values get concatenated. Instead: Keep values out of the string and pass them as declared parameters: EXEC sys.sp_executesql @sql, N'@CustomerId int, @From date', @CustomerId = @CustomerId, @From = @From; where @sql contains WHERE CustomerId = @CustomerId AND OrderDate >= @From.dbo.TableName.sp_executesql statements are cached and reused just as well. Instead: Choose procedures for other reasons (security, deployment), not caching.Plan reuse is a CPU and memory trade: you save compilation and pay with one plan for all values. For OLTP the trade is almost always right, so parameterised SQL is the default and the work is in spotting where it's broken: concatenated SQL, variable parameter lengths, unqualified names and SET option differences. Newer versions change the picture slightly: PSP optimisation (SQL Server 2022, compat 160) caches a dispatcher plan with up to three variants, and OPPO (2025) does similar for optional parameters, so one query can legitimately hold several cached plans.
I measure before acting: compilations vs batch requests, single-use plan memory, and plans per query_hash. Forced parameterisation is a scalpel for code you can't change, not a server default. Optimize for ad hoc workloads is low-risk for most servers, but it isn't free: every statement that runs exactly twice compiles twice, and plan cache DMVs show stubs without plans for first runs, so check the single-use ratio first and confirm the effect afterwards.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Parameterised app SQL | Always | Sniffing on skewed data | Never avoid it |
| Optimize for ad hoc workloads | High share of single-use plans (reporting, tools) | Second execution compiles again; first-run plans not visible in cache | Workloads that are almost all parameterised (little gain) |
| Forced parameterisation | Vendor app with literal SQL | Sniffing, filtered index mismatch | Apps you can fix |
| Plan guide template | One problematic query shape | Hidden, brittle | When code change is possible |
OPTION (RECOMPILE) |
Deliberately avoid caching for skewed queries | Compile every time | Hot paths |
AddWithValue infers the parameter type from the .NET value: a string becomes nvarchar(n) where n is that value's length, so 'Smith' is sent as nvarchar(5) and 'Nguyen' as nvarchar(6). The parameter declaration is part of the statement text, so SQL Server compiles and caches a separate plan per length. On a busy system that means extra compile CPU, plan cache memory taken from the buffer pool, and useful plans evicted sooner. If the column is varchar, the same call also causes a CONVERT_IMPLICIT scan.
Detect it as many rows sharing one query_hash with different plan_handles in sys.dm_exec_query_stats, or many query ids for one query in Query Store. Fix with Parameters.Add("@p", SqlDbType.VarChar, 20); Dapper and EF Core already send fixed sizes.
This is almost always parameter sniffing. SQL Server compiled the plan for the first parameter values it saw, maybe a tiny customer, and now reuses it for a customer with 2 million rows. SSMS looks fast because it runs with SET ARITHABORT ON (the app's SqlClient uses OFF), so it gets a separate cache entry and compiles a fresh plan for my values.
I confirm it in Query Store: the regressed query, two plan ids, and in the plan XML ParameterCompiledValue vs ParameterRuntimeValue. Mitigate by forcing the good plan. Then fix properly: OPTION (RECOMPILE) for infrequent queries, OPTIMIZE FOR, a Query Store hint, splitting code paths, or an index that makes one plan good for everyone. SQL Server 2022's PSP optimisation helps some cases.
SQL Server parses the statement (syntax), binds it (the algebriser resolves tables, columns, types and permissions into a query tree), then checks the plan cache. On a miss the optimiser runs: simple statements get a trivial plan; everything else goes through cost-based optimisation, exploring alternative join orders, join types and access paths using cardinality estimates derived from statistics. It picks the cheapest plan it finds within a time budget, caches it, and the execution engine runs it.
The trade-off: plan reuse saves CPU on compilation, but one cached plan serves every later parameter value, good or bad.
How to tell it (STAR)
**S:** Our SQL Server was running hot at [70%] CPU with no obvious heavy query, and OLTP latency was creeping up. **T:** I was asked to find where the CPU was going. **A:** Compilations per second were almost equal to batch requests, so I looked at the plan cache and found [45,000] single-use plans using nearly [4 GB], mostly from five query shapes in our reporting service that concatenated values into SQL. I turned on optimize for ad hoc workloads as a stopgap, then rewrote the query builder to use sp_executesql with typed parameters, and added an analyser rule against AddWithValue. **R:** Single-use plan memory fell to under [200 MB], CPU dropped by about [25%], and we closed a SQL injection risk at the same time.
Last updated 23 Nov 2026.