The symptom
A parameterized query is compiled once and its plan is cached. To build that plan the optimizer looks at the parameter values of the call that triggered compilation, which is called sniffing. Most of the time that is what you want. It goes wrong when the data is skewed: a plan built for a customer with 20 orders is reused for a customer with 40,000, or the other way round.
The signs are a query that is fast or slow depending on who ran it first, performance that changes after a restart, a failover or a statistics update, and a query that is slow from the application but fast when you paste it into a query window with the values typed in. The query plan viewer reports a SQL Server plan whose compiled and runtime parameter values differ and whose row estimates are far off. The examples use a shop schema with 400,000 orders: customer 1 has 40,000 of them, every other customer about 20.
Diagnose it
SQL Server: reproduce it with two calls
CREATE INDEX IX_Orders_CustomerId ON dbo.Orders (CustomerId);
GO
CREATE OR ALTER PROCEDURE dbo.GetCustomerOrders @CustomerId int
AS
SELECT OrderId, Total, Reference FROM dbo.Orders WHERE CustomerId = @CustomerId;
GO
SET NOCOUNT ON;
SET STATISTICS IO ON;
GO
EXEC dbo.GetCustomerOrders @CustomerId = 4242;
GO
EXEC dbo.GetCustomerOrders @CustomerId = 1;
Table 'Orders'. Scan count 1, logical reads 63, physical reads 0
Table 'Orders'. Scan count 1, logical reads 120073, physical reads 0
The first call compiled a plan for a customer with 20 orders: an index seek and a key lookup per row. The second call reused it for 40,000 rows and paid for 40,000 lookups. Now clear the plan and call in the other order:
EXEC sp_recompile 'dbo.GetCustomerOrders';
GO
EXEC dbo.GetCustomerOrders @CustomerId = 1;
GO
EXEC dbo.GetCustomerOrders @CustomerId = 4242;
Table 'Orders'. Scan count 1, logical reads 2579, physical reads 0
Table 'Orders'. Scan count 1, logical reads 2579, physical reads 0
This time the plan was built for customer 1 and scans the table, which is right for 40,000 rows and wasteful for 20. Neither plan is wrong; each is wrong for the other value.
SQL Server: compiled value against runtime value
An actual execution plan records both values. In Management Studio they are in the properties of the root operator under Parameter List. In the XML:
EXEC sp_recompile 'dbo.GetCustomerOrders';
GO
EXEC dbo.GetCustomerOrders @CustomerId = 4242;
GO
SET STATISTICS XML ON;
GO
EXEC dbo.GetCustomerOrders @CustomerId = 1;
GO
SET STATISTICS XML OFF;
<ColumnReference Column="@CustomerId" ParameterDataType="int" ParameterCompiledValue="(4242)" ParameterRuntimeValue="(1)" />
A compiled value that differs from the runtime value, on a plan whose estimated rows are far from the actual rows, is the proof. A plan taken from the cache has only the compiled value. That is still useful: it tells you which call the plan was built for.
PostgreSQL: custom and generic plans
PostgreSQL works the other way round. For a prepared statement it plans each of the first five executions with the actual values (a custom plan). After that it may switch to a generic plan, built without looking at any value, if the generic plan does not look more expensive than the custom ones did on average. A generic plan shows the parameter as $1 where a custom plan shows the value:
CREATE INDEX orders_customer_idx ON orders (customer_id);
PREPARE customer_orders (int) AS
SELECT order_id, total, reference FROM orders WHERE customer_id = $1;
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
EXECUTE customer_orders (1);
SET plan_cache_mode = force_generic_plan;
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
EXECUTE customer_orders (1);
Bitmap Heap Scan on orders (cost=458.91..5435.25 rows=39547 width=17) (actual rows=40000.00 loops=1)
Recheck Cond: (customer_id = 1)
-> Bitmap Index Scan on orders_customer_idx (cost=0.00..449.02 rows=39547 width=0) (actual rows=40000.00 loops=1)
Index Cond: (customer_id = 1)
Bitmap Heap Scan on orders (cost=4.60..91.95 rows=23 width=17) (actual rows=40000.00 loops=1)
Recheck Cond: (customer_id = $1)
-> Bitmap Index Scan on orders_customer_idx (cost=0.00..4.60 rows=23 width=0) (actual rows=40000.00 loops=1)
Index Cond: (customer_id = $1)
The generic plan expects the average customer, 23 rows, and gets the largest one. The scan happens to have the same shape here; in a larger query that estimate decides the join method and join order above it. To see which kind your sessions are running, pg_prepared_statements counts both for the current session:
SELECT name, generic_plans, custom_plans FROM pg_prepared_statements;
name | generic_plans | custom_plans
customer_orders | 1 | 1
Fix it
Give the query a plan that suits every value
Sniffing only hurts when different values need different plans. Often an index change removes the difference. Here the two plans differ because the index does not cover the query; once it does, a seek is the best plan for any customer and there is nothing left to get wrong:
CREATE INDEX IX_Orders_CustomerId ON dbo.Orders (CustomerId)
INCLUDE (Total, Reference) WITH (DROP_EXISTING = ON);
GO
EXEC dbo.GetCustomerOrders @CustomerId = 4242;
GO
EXEC dbo.GetCustomerOrders @CustomerId = 1;
Table 'Orders'. Scan count 1, logical reads 3, physical reads 0
Table 'Orders'. Scan count 1, logical reads 170, physical reads 0
SQL Server: recompile the statement
OPTION (RECOMPILE) builds a fresh plan for the values of every call. It always gets the right plan and always pays for a compilation, so it suits queries that run a few times a minute, not thousands of times a second.
DROP INDEX IX_Orders_CustomerId ON dbo.Orders;
CREATE INDEX IX_Orders_CustomerId ON dbo.Orders (CustomerId);
GO
CREATE OR ALTER PROCEDURE dbo.GetCustomerOrders @CustomerId int
AS
SELECT OrderId, Total, Reference FROM dbo.Orders WHERE CustomerId = @CustomerId
OPTION (RECOMPILE);
GO
EXEC dbo.GetCustomerOrders @CustomerId = 4242;
GO
EXEC dbo.GetCustomerOrders @CustomerId = 1;
Table 'Orders'. Scan count 1, logical reads 63, physical reads 0
Table 'Orders'. Scan count 1, logical reads 2579, physical reads 0
SQL Server: plan for the average value
OPTIMIZE FOR UNKNOWN tells the optimizer to ignore the sniffed value and use the average number of rows per value. Every call gets the same plan whatever ran first. That makes performance predictable; it does not make the plan good for the unusual value.
CREATE OR ALTER PROCEDURE dbo.GetCustomerOrders @CustomerId int
AS
SELECT OrderId, Total, Reference FROM dbo.Orders WHERE CustomerId = @CustomerId
OPTION (OPTIMIZE FOR UNKNOWN);
GO
EXEC dbo.GetCustomerOrders @CustomerId = 1;
GO
EXEC dbo.GetCustomerOrders @CustomerId = 4242;
Table 'Orders'. Scan count 1, logical reads 120073, physical reads 0
Table 'Orders'. Scan count 1, logical reads 63, physical reads 0
The database-wide version of this hint is the PARAMETER_SNIFFING database scoped configuration. When one specific plan is known to be acceptable for all values, Query Store can force it without a code change, and the plan regressions snippet finds queries whose plan changed for the worse.
PostgreSQL: force custom plans
When a generic plan is the problem, tell PostgreSQL to plan with the actual values every time:
SET plan_cache_mode = force_custom_plan;
EXPLAIN (ANALYZE, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
EXECUTE customer_orders (1);
DEALLOCATE customer_orders;
RESET plan_cache_mode;
Bitmap Heap Scan on orders (cost=458.91..5435.25 rows=39547 width=17) (actual rows=40000.00 loops=1)
Recheck Cond: (customer_id = 1)
-> Bitmap Index Scan on orders_customer_idx (cost=0.00..449.02 rows=39547 width=0) (actual rows=40000.00 loops=1)
Index Cond: (customer_id = 1)
The setting can be applied to a session, a role or a database, so it can be limited to the application that needs it. The cost is planning time on every execution.
When to leave it alone
Sniffing is the normal, useful behaviour, and a compiled value that differs from the runtime value is not a problem by itself: that is true of nearly every cached plan. Leave it when the row estimates are close to the actual counts, or when both values would get the same plan. Do not turn sniffing off for a whole database because one procedure misbehaves.
The checklist
Work through it in order. Each step gives you the evidence for the next one.
- Compare the compiled and runtime parameter values in the actual plan (SQL Server).
- Check that estimated and actual rows differ widely on the operators that use the parameter.
- Run the query with a common value and with an unusual one, after clearing its plan, to see both plans.
- First try an index that makes one plan good for every value.
- Otherwise recompile per call for infrequent queries, or plan for the average for frequent ones.
- In PostgreSQL, check pg_prepared_statements and try plan_cache_mode = force_custom_plan.
Questions that come up
What is parameter sniffing?
When SQL Server compiles a parameterized query or procedure, it uses the parameter values of that first call to estimate row counts, then caches the plan and reuses it for later calls. The plan is tuned for the first values. It becomes a problem only when other values need a different plan.
Why is the query fast in Management Studio and slow from the application?
Usually because the two are not sharing a plan. Session settings such as ARITHABORT differ between Management Studio and most client libraries, so each gets its own cached plan, compiled for different parameter values. Typing literal values instead of parameters also produces a different plan.
Does restarting or updating statistics fix parameter sniffing?
It clears the cached plan, so the next call compiles a new one for whatever values it happens to carry. That may fix the symptom or bring it back. It explains why the problem seems to come and go.
Is OPTION (RECOMPILE) safe to use?
It is safe and gives each call a plan built for its own values. The cost is a compilation on every execution, which adds CPU time. Use it on queries that run occasionally and take long enough that compile time does not matter.
Does PostgreSQL have parameter sniffing?
Not in the same form. PostgreSQL plans a prepared statement with the real values for its first five executions and then may switch to a generic plan that ignores them. The equivalent problem is a generic plan that is poor for unusual values, and plan_cache_mode controls it.