Parameter Sensitive Plan Optimization in SQL Server: A Course in Six Parts
Since SQL Server 2022, PSP optimization is meant to ease an old problem: parameter sniffing. A query gets a plan that fits one value and fails for another. Parameter Sensitive Plan Optimization, often called PSPO, stores several plans for the same query. It is on by default at compatibility level 160.
If you moved a database to level 160, PSP optimization is on. Whether it applies to your own queries only shows on close inspection. The answer depends on conditions that Microsoft documents only in part. This course builds the understanding in six parts. Each part has a learning goal, an experiment you can repeat, and questions at the end to check your understanding.
In short
- PSP optimization creates up to three plans for one query parameter, the variants: one for rare, one for medium and one for frequent values. A plan component called the dispatcher picks the right one on each call. With several parameters, there can be more variants.
- It applies only under conditions. The most important ones: compatibility level 160 or higher, an equality comparison with a parameter, and a strongly skewed distribution of values in the statistics.
- It does not solve the problem completely. Values in the middle range still share one variant.
- It changes what you see in the plan cache and in Query Store. One query becomes several. If you filter Query Store only by a procedure’s object ID, you miss the variants: their
object_idis 0.
Who this course is for
The course is for database administrators and developers who can read execution plans and know T-SQL. You do not need to know statistics or histograms; part 2 builds that up.
For the experiments you need:
- a test instance with SQL Server 2022 or 2025, such as the Developer Edition; the course does not cover Azure SQL Database,
- SQL Server Management Studio or another tool that processes
GOand showsSTATISTICS IO, - about 600 MB of free space: in the lab, the course database used 264 MB for data and 328 MB for the log,
- the permission to create a database; in your own course database you are the owner and may do everything the experiments need.
Warning: Run the experiments only on a test instance. They clear the plan cache of the course database and change database settings.
The learning path
Status: Parts 1 to 3 have been released, parts 4 to 6 follow.
| Part | Topic | Learning goal: afterwards you can … |
|---|---|---|
| 1 | One plan for all values | explain why a stored plan fits one value and fails for another |
| 2 | How SQL Server knows that values are unevenly distributed | read a histogram and predict how many rows SQL Server estimates for a value |
| 3 | Dispatcher and variants | recognize a plan with PSP optimization and determine which variant a value gets |
| 4 | When does PSP optimization apply, and when not? (coming) | predict and verify whether SQL Server creates variants for a query |
| 5 | Finding variants in the plan cache and in Query Store (coming) | find queries with variants on your own server and assign them correctly |
| 6 | When variants are not enough (coming) | decide when PSP optimization is enough and when another remedy fits better |
The parts build on each other. If you already know parameter sniffing well, you can skim part 1, but you should still build the course database.
The course database
All parts use the same database, PspKurs. It contains an orders table and deliberately very uneven customers. The course database uses German object names; Bestellungen means orders, KundeId customer ID, Betrag amount, Kunden customers. The result columns of the procedure are Bestellungen (number of orders) and Umsatz (revenue).
| Customers | Orders per customer | Purpose |
|---|---|---|
| 19,997 one-off customers | 1 | the normal case: many customers with little data |
| 3333, 15000, 7777 among the one-off customers | 10, 100, 1,000 | a few larger customers among many small ones |
| 600 regular customers (30001 to 30600) | 10 to 1,000 | more customers than the histogram has steps (part 2) |
| 20001 to 20008 | 10, 99, 100, 101, 1,000, 10,000, 100,000, 500,000 | boundary cases for the variants (part 3) |
In addition there are two tables with about 100,000 rows each, on which part 4 shows the threshold of PSP optimization, and the table dbo.Grenzen with seven values for the boundary cases in part 3. The table dbo.Bestellungen has a clustered index on the order number and two nonclustered indexes, one on KundeId and one on ProduktId, which contain only that column. To sum Betrag, SQL Server must therefore either look up each order in the clustered index or read the whole table. This choice makes the procedure sensitive to the value of @KundeId.
Almost all experiments use this procedure. It is part of the setup script; you do not need to create it separately.
-- Excerpt from the setup script, do not run on its ownCREATE OR ALTER PROCEDURE dbo.Bestellungen_Kunde @KundeId intASBEGIN SET NOCOUNT ON; SELECT COUNT(*) AS Bestellungen, SUM(Betrag) AS Umsatz FROM dbo.Bestellungen WHERE KundeId = @KundeId;END;To build the course database:
- Open a connection to your test instance.
- Run the setup script. It creates
PspKursand stops if the database already exists. - Check the last line of the output. It must read:
Bestellungen 780417 | Kunden 20608 | Grad 160.
The setup script also turns on Query Store in PspKurs. Part 5 needs it.
To clean up, run the script aufraeumen-psp-kurs.sql. It disconnects open connections to PspKurs and drops the database with all its data. It drops the database only if it carries the course marker.
Terms in this course
The course uses each term with exactly one meaning:
| Term | Meaning |
|---|---|
| PSP optimization | Parameter Sensitive Plan Optimization, since SQL Server 2022 |
| compile | create an execution plan for a query |
| dispatcher | the plan component that assigns the value to a variant on each call; in the plan XML, the Dispatcher element |
| variant | a separate plan for a span of estimated row counts; recognizable in the plan XML by QueryVariantID |
| step boundary | the value that ends a histogram step (RANGE_HI_KEY); the statistics store its row count |
| range | the values of a histogram step before its step boundary; the statistics store only an average for them |
| boundary value | the estimated row count at which the dispatcher switches to the next variant |
| threshold | the condition from which SQL Server applies PSP optimization at all |
| skew | how unevenly the values of a column are distributed |
| pages read | page accesses from SET STATISTICS IO (logical reads); if a plan reads the same page several times, each access counts |
Does this affect me?
PSP optimization can only apply in databases that run at compatibility level 160 or higher and in which both it and parameter sniffing are turned on. The following query shows this for the current database. If Query Store is running, it also counts the queries for which it has already stored variants.
The query runs on SQL Server 2022 and later; earlier versions have no PSP optimization. It needs the VIEW DATABASE PERFORMANCE STATE permission in the database and only reads.
-- Am I affected by PSP optimization? Current database, SQL Server 2022 and later, read-only.SELECT DB_NAME() AS datenbank, d.compatibility_level AS kompatibilitaetsgrad, (SELECT CONVERT(int, value) FROM sys.database_scoped_configurations WHERE name = N'PARAMETER_SENSITIVE_PLAN_OPTIMIZATION') AS psp_eingeschaltet, (SELECT CONVERT(int, value) FROM sys.database_scoped_configurations WHERE name = N'PARAMETER_SNIFFING') AS parameter_sniffing, qs.actual_state_desc AS query_store, CASE WHEN qs.actual_state_desc IN (N'READ_WRITE', N'READ_ONLY') THEN (SELECT COUNT(DISTINCT parent_query_id) FROM sys.query_store_query_variant) END AS abfragen_mit_variantenFROM sys.databases AS dCROSS JOIN sys.database_query_store_options AS qsWHERE d.database_id = DB_ID()OPTION (MAXDOP 1);How to read the result:
kompatibilitaetsgrad160 or higher,psp_eingeschaltetandparameter_sniffingboth 1: SQL Server can create variants. Whether it does depends on the conditions that part 4 shows.abfragen_mit_variantenempty: Query Store is off. The query then cannot tell you anything about variants; PSP optimization still works.abfragen_mit_varianten0: Query Store has not stored any query with variants. The plan cache may still hold some.- On SQL Server 2025 with level 170, the last column also counts variants of Optional Parameter Plan Optimization (OPPO). It uses the same technique.
How to use the course
- Build the course database on a test instance.
- Read the parts in the order of the learning path.
- In each part, answer the prediction question before you run the experiment.
- Compare your result with the result in the text.
- If your result differs clearly, check the version and the compatibility level.
- At the end of each part, answer the questions that check your understanding.
Sources
- Microsoft: Parameter Sensitive Plan Optimization
- Microsoft:
sys.query_store_query_variant - Microsoft: ALTER DATABASE SCOPED CONFIGURATION
- Microsoft: Optional Parameter Plan Optimization
- Paul White: Parameter Sensitive Plan Optimization Thresholds (January 2025); we re-measured the thresholds described there on our versions, and not all of them held up (part 4)
Next: Part 1: One plan for all values · Background in depth: Understanding Parameter Sniffing in SQL Server