I found that the if I query the table with less than or greater than operator, sql server indexes do not work properly.
Say I have a simple table (TestTable) with only 2 columns like this:
Column Name, column type, primary Key, index
iID, int, yes, cluster index
iCount, int, no, non-cluster index
name, nvarchar(255), no, no index
Now, I query the table by this:
SELECT * FROM TestTable WHERE iCount = 10.
Very good, Sql server will use the non-cluster index for column iCount to retrieve the result.
However, if I query the table by this:
SELECT * FROM TestTable WHERE iCount < 10,
Sql server will do a index scan over the cluster index for the iID to retrieve the result.
I am wondering why sql server is not able to use proper index when I use less than or greater than operator in the query.
If the table has very few rows, it is cheaper for SQL Server to scan the clustered index rather than using the non-clustered index and then doing a lookup for the rest of the columns in the clustered index. If that’s the case, change the query to SELECT iCount FROM… and you should see the query plan change to using the index as you are expecting.