I have a simple query like
select count(distinct key)
from table
where date between '2014-01-01' and '2014-12-31'
It's fast (about 1 second), but becomes much slower (about 4 seconds) when I try to parameterize it within sp_executesql
:
exec sp_executesql
N'select count(distinct key) from table where date between @start and @end',
N'@start date, @end date',
@start = '2014-01-01', @end='2014-12-31'
Why the difference in performance?
UPDATE The plan difference appears to be because of type conversion. When I change the parameter types to N'@start datetime, @end datetime', to match the columns exactly, the discrepancy disappears, and the plans for parameters vs. constants are practically identical (same costs, etc.) (Facepalm.)
I'll accept an answer that explains why the type conversion results in such a dramatic plan difference rather than just converting the parameters up front and proceeding as usual.
END UPDATE
The plans are very similar - same index, same estimated cardinalities, same row counts, and same I/O - although the CPU cost estimates in the parameterized version are higher.
Specific discrepancies:
- The same Index Seek appears in both plans, but it is parallel in the (fast) version with literals, and NOT parallel in the (slow) version with parameters. The non-parallel one has higher CPU estimate.
- The version with parameters has an Nested Loop join connecting the index scan with some logic around parameters. This appears to add some CPU overhead of its own (CPU estimate = 7.6 on the nested loop).
- Both versions have "Parallelism" as a child of the Hash Match; in the parameterized version it is Distribute Streams (CPU estimate = 16.5) but in the literal version it is Repartition Streams (CPU estimate = 8.3)
How can I get the parameterized version to perform similarly as the version with literals?
All I could find in my research about performance of parameterized queries has to do with estimates -- either plans cached with different parameter values, or local variables being treated as unknowns. Neither is a factor here; my estimates are correct.