Curtis Swartzentruber

in

Datatype mismatches: SQL Server performance tip

I ran into a very interesting find the other day while trying to optimize some queries by studying the execution plans.  We have a bunch of stored procedures that use an underlying view that points to a single table.  This table has an "item_id" key and often we use that key in the WHERE clause or for joins.

As there was an existing clustered index on that column, I couldn't figure out why I was always getting table scans on the underlying table.  In other words, the query engine was completely ignoring the index or deciding not to use it.

I ran a simplified version of the query with the item_id hard-coded and all of a sudden it did use the index, giving me a huge performance boost because the table is a bit large.  Not millions of rows large, but relatively large for our application.  That got me thinking about datatypes, so I decided to check the underlying table.  Numeric(8,0).  Hmmm.  We are using int everywhere. Surely that is a simple enough implicit conversion to not cause issues, right?  Wrong.  Once I changed my input parameters on the stored procedures to use numeric(8,0) instead of int, I started getting nice clustered index seeks everywhere.  Bingo.  I've seen this type of thing before, but generally it is a more drastic conversion or comparison like datetime vs varchar or int vs char or something like that.

Anyway, another weird performance tip that is certainly not intuitive.  This is on SQL Server 2000, not sure if the same behavior exists in SQL Server 2005 or newer.

Comments

spoov said:

Is your SQL server on SP3? If so try applying SQL server 2000 service pack 4 from here... http://www.microsoft.com/downloads/details.aspx?familyid=8e2dfc8d-c20e-4446-99a9-b7f0213f8bc5&displaylang=en

On a side note, I just found out that MS just released a new hotfix today along with the final build of SP4, see if you are affected by this: http://support.microsoft.com/default.aspx?kbid=899761
# November 2, 2007 11:04 AM