I have a table with two indices; one is a multi-column clustered index, on a 3 columns:
(
symbolid int16,
bartime int32,
typeid int8
)
The second is non clustered on
(
bartime int16
)
The select statement i'm trying to run is:
SELECT symbolID, vTrdBuy
FROM mvTrdHidUhd
WHERE typeID = 1
AND barDateTime = 44991
AND symbolid in (1010,1020,1030,1040,1050,1060)
I run this query on sql2008 using sql management studio editor and enabling actual execution plan, I found that the sql uses the second index and propse to create a new index for the three columns (symbolid,bartime,typeid) but nonclustered!!! (I think it sayes non clustered index as there is already clustered one)
This selection is wrong, again I rerun the same query and forced SQL to use the clusted index (using "with index") and performance is better as it should.
I have two questions here one related to this behavior and the second for the query itself
- Why SQL chooses wrong index and propse the same index
- Which one I should use in the
"where"
condition for better performance
symbolid in (1010,1020,1030,1040,1050,1060)
(symbolid = 1010 or symbolid = 1020 ..etc)
(symbolid between (1010 and 1060))
After Testing
I found that when I change the where condition from using IN to use >= and <=the non clustered index on bartime column gives better performance than clustered index on 3 columns.
SO I have two cases if the WHERE uses IN it is better to use the clustered index, if it contains >= and <= it uses the second one.