How To Improve SQL Server Query Performance by Using Indexes

Description

Performance of queries against SQL Server can be affected by string arguments due to an issue with the SQL Server optimizer.

Discussion

It appears that when a query has a string value argument, the SQL Server optimizer does not always see the type as matching some types of columns (for example CHAR columns with a fixed size). As a result, the optimizer will ignore indexes and hints to use them and resort to a table scan.

For example:

SELECT AmountDue, AmountPaid, AccountNumber FROM Invoices WHERE AmountDue > 0 and CustomerId = :CustomerId

If CustomerId is defined in the database as Char(5), the optimizer may not recognize the :CustomerId argument contains a matching value because the type of the argument is VARCHAR.

In such cases, adding a CAST to the argument value causes the optimizer to choose the appropriate index because the types match:

SELECT AmountDue, AmountPaid, AccountNumber FROM Invoices WHERE AmountDue > 0 and CustomerId = CAST(:CustomerId AS CHAR(5))