Query Tuning Implicit Conversion
Contents
What are implicit conversions
An implicit conversion is when SQL Server has to convert from one data type to another data type to be able to make a comparison.
Generally, implicit conversions are most problematic when they turn what could have been an index seek into an index scan. Implicit conversion can also affect cardinality estimates.
Often this is a issue that can be fixed relatively easily.
Sample Data
This sample code creates a table with 1,000,000 rows.
|
|
Demo of the Problem
Here field1 and ‘jahbah’ are both varchar values so no data type conversion is needed, and if we view the actual plan we see it did an index seek.
|
|
Now let’s change the prior query ever so slightly and make ‘jahbah’ an nvarchar value. This time we see an index scan. On a million row table, we probably care that it is an index scan when we are just trying to return one row.
|
|
Notice the warning symbol on the SELECT operator. Hovering over it reveals the message:
Type conversion in expression (CONVERT_IMPLICIT(nvarchar(10),[MyDatabase].[dbo].[MyImplicitConversionExample].[field1],0)=[@1]) may affect “SeekPlan” in query plan choice
Now let’s change the prior query to include an explicit conversion, and we get an index seek. This would be one way to fix the implicit conversion problem.
|
|
Finding instances of implicit conversion
- You may note it in a query plan you are reviewing perhaps because you were looking at queries with high read counts.
- Capture the
sqlserver.plan_affecting_convert
event using an Extended Events session. - Query the DMV
sys.dm_exec_query_stats
,cross apply sys.dm_exec_query_plan(plan_handle)
, and look for instanceswhere query_plan like '%CONVERT_IMPLICIT%'
.