Avoid Unnecessary Data Type Conversions

SQL Server adds implicit data type conversions when types don’t match.  This can have unintended results both on query results, but also on the query plan.  It is important to use literal constants that match in type column they are being compared with wherever possible.  A common mistake in writing T-SQL is to always use string literals for constants even when those constants are numbers, for example.


WHERE Quantity = ‘100’

In this example, ‘100’ is a character string while the column Quantity is an integer.  The implicit conversion used follows strict precedence rules.  Here the conversion will be on Quantity to character string, and not on the ‘100’ to an integer. 

Comments (2)

  1. diegov says:

    Ian José, I think it is even worse when you do the oposite:

    SELECT Quantity FROM Sales WHERE Status = 1

    Status being a string column. Unfortunatelly SQL Server will let you do this until some day someone adds a status code in a row that cannot be converted to a number!

    Add to this the fact that SqlCommand.ExecuteScalar sometimes fails to raise an error on this condition, and you have a bug that is very difficult to chase (I know because this have just happened in my company).

    My wish: that I could disable implicit conversions by using some phrase in the connection string. Kind of "Option Strict = True;" 🙂

Skip to main content