📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How does the SQL Server plan cache work? Explain how plans are matched and reused, simple versus forced parameterisation, why SQL built by string concatenation bloats the cache, and how sp_executesql and 'optimize for ad hoc workloads' help.

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.

Mid-Level Theory Intermediate ado-net parameterisation plan-cache query-performance sp-executesql sql-server

🎯 Key points

  • Plans are matched on exact statement text hash plus plan-affecting attributes (SET options, database, and the user's default schema when names aren't schema-qualified)
  • objtype: Adhoc (literals), Prepared (sp_executesql / parameterised), Proc (stored procedures)
  • Simple parameterisation only auto-parameterises trivial-plan-safe queries; most literal queries stay Adhoc
  • Forced parameterisation replaces literals database-wide: fewer compiles, but every query becomes a sniffing candidate and filtered indexes may stop matching
  • Concatenated SQL creates thousands of single-use plans: compile CPU, memory taken from the buffer pool, cache churn
  • sp_executesql with typed parameters (and fixed parameter lengths) gives one reusable plan and prevents SQL injection
  • 'optimize for ad hoc workloads' stores a small stub on first run and the full plan only on the second; PSP (2022) caches a dispatcher plan plus up to 3 variants
  • Measure with sys.dm_exec_cached_plans (usecounts = 1, size_in_bytes) and grouping by query_hash

⏱ 30-second answer

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.

  • Simple parameterisation (default) only auto-parameterises very simple, safe queries.
  • Forced parameterisation replaces most literals with parameters, cutting compiles but adding parameter sniffing.

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 = 42 and WHERE CustomerId = 43 are two different statements and two different plans. In sys.dm_exec_cached_plans you see them as objtype Adhoc. Parameterised statements sent through sp_executesql, which is what SqlClient does when you add parameters, are Prepared, and stored procedures are Proc.

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 is AddWithValue with strings: SqlClient sizes the parameter from the value, so nvarchar(5) and nvarchar(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."


Plan cache object types

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

Parameterisation options

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)

Production example

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%.

🔍 What the interviewer is checking

Checks whether the candidate understands how plan reuse works and can connect application data-access code to SQL Server CPU and memory.

Green flags

  • Explains the text-hash cache key and SET options.
  • Distinguishes simple from forced parameterisation and their risks.
  • Spots AddWithValue length variance and concatenated SQL.
  • Measures with sys.dm_exec_cached_plans and query_hash.

Red flags

  • Thinks only stored procedures get cached plans.
  • Suggests flushing the cache regularly.
  • Ignores the SQL injection angle of concatenation.

📚 Learn in depth

1. What gets cached and how it's found

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.

2. Simple parameterisation

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.

3. Forced parameterisation

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.

4. The cost of single-use plans

  • Compilation CPU: tens to hundreds of milliseconds for complex queries.
  • Memory: the cache comes from the same memory as the buffer pool; plan cache limits are a percentage of target memory, and a cache full of junk evicts useful plans.
  • Contention: high compile rates can cause 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.

5. Parameter length variance

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.

6. Measuring cache health

  • 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.
  • Perfmon/sys.dm_os_performance_counters: SQL Compilations/sec vs Batch Requests/sec (a ratio above about 10% warrants a look).

Try it yourself

  1. Run the same query with 100 different literals and count Adhoc plans for it in sys.dm_exec_cached_plans.
  2. Repeat with sp_executesql and confirm one Prepared plan with usecounts = 100.
  3. Use AddWithValue with strings of different lengths from a small C# console app and count the plans.
  4. Enable optimize for ad hoc workloads and look for Compiled Plan Stub entries.
  5. Group sys.dm_exec_query_stats by query_hash and find shapes with more than 50 plans.

💻 Code

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);
    }
}

⚠ Common mistakes

  • Mistake: Building SQL with string concatenation or interpolation. Why it is wrong: SQL injection plus a new plan per value. Instead: Use parameters (sp_executesql, Dapper, EF Core).
  • Mistake: Using 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).
  • Mistake: Using 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.
  • Mistake: Turning on forced parameterisation as a general tuning knob. Why it is wrong: Literal queries that used to get value-specific plans now share one sniffed plan, so skewed queries can regress badly, and queries that relied on literals to match filtered indexes lose them. Instead: Fix the app, or use a plan guide for one query shape, with Query Store watching for regressions.
  • Mistake: Not schema-qualifying object names. Why it is wrong: The plan isn't cached 'per user' as such, but when names are unqualified the user's default schema becomes part of the cache key, so identical text from users with different default schemas produces separate plans. Instead: Always use dbo.TableName.
  • Mistake: Clearing the whole plan cache to 'fix' bloat. Why it is wrong: It causes a recompile storm and the bloat returns. Instead: Fix the source; clear only specific entries if needed.
  • Mistake: Thinking stored procedures are required for plan reuse. Why it is wrong: sp_executesql statements are cached and reused just as well. Instead: Choose procedures for other reasons (security, deployment), not caching.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions AddWithValue or parameter types Why: Checks depth on parameter length variance and implicit conversion together
    How to answer

    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.

  2. When: Candidate says reuse means one plan for all values Why: Checks how they diagnose and fix parameter sniffing
    How to answer

    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.

  3. When: Candidate mentions compilation cost Why: Checks understanding of what compilation actually involves
    How to answer

    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 optimiser never runs the query to cost it; every cost is an estimate.
    • Search space grows factorially with joins, so it settles for good enough.

    The trade-off: plan reuse saves CPU on compilation, but one cached plan serves every later parameter value, good or bad.

🛠 Real-world problems: how you handle them

Reporting service fills the plan cache with single-use plans
Situation
A [reporting service] built search SQL by concatenating filter values, running against [SQL Server 2022 on a 64 GB VM] shared with the main OLTP database.
Signals
CPU sat at [70%] with no single heavy query; SQL Compilations/sec was close to Batch Requests/sec; Page Life Expectancy dropped; OLTP queries became intermittently slower as their plans were evicted.
Investigation
`sys.dm_exec_cached_plans` showed [45,000] Adhoc plans with `usecounts = 1` using [3.8 GB]. Grouping `sys.dm_exec_query_stats` by `query_hash` found five query shapes with thousands of plans each, all from the reporting service. A second smaller source was `AddWithValue` producing a separate plan per string length.
Resolution
Immediate: enabled optimize for ad hoc workloads and cleared single-use Adhoc plans with `DBCC FREESYSTEMCACHE('SQL Plans')` once at a quiet time. Real fix: rewrote the query builder to use `sp_executesql` with typed, fixed-length parameters and a whitelist for sort columns.
Prevention
A Roslyn analyser rule flags `AddWithValue` and string-built SQL; a dashboard tracks compilations/sec ratio and single-use plan memory with an alert at [500 MB]; code review checklist item for dynamic SQL.

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.

↩ Usually asked after

More in Query Performance

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me