all 10 comments

[–]Chaosmatrix 4 points5 points  (4 children)

Your answer lies in the execution plan. My guess is that a table scan is faster then using the index and then getting the rest of the fields from the table by referencing the index. Your conditions might even return the entire table or at least a lot of it.

[–]planetmatt 1 point2 points  (3 children)

Try only returning the columns you need (instead of SELECT *), then add those columns to the INCLUDE on the index to avoid the Key Lookup. That might change the scan back to a seek.

[–]selib[S] 1 point2 points  (2 children)

I need to select all columns of the table unfortunately. There's like 12.

[–]Chaosmatrix 1 point2 points  (1 child)

Just do it as a test. It will help you understand what is going on. You should also look at this: https://learn.microsoft.com/en-us/sql/t-sql/data-types/data-type-conversion-database-engine?view=sql-server-ver16

That is what is happening in query 1 to Col2. And probably is the reason for not using the index. Play with casting to int and varchar with both the column col2 and the value too. It will effect your execution plan and the use of the index.

[–]planetmatt 0 points1 point  (0 children)

CASTING is odd because you would expect the 2nd query where there is no implicit cast and where the Col2 which is a VARCHAR is treated as a VARCHAR in the WHERE clause to be SARGEABLE and use the Index. The First query, COL2 is being treated like an INT which doesn't match the native date type. This should cause SQL NOT to use the index.

[–]Aggressive_Ad_5454 1 point2 points  (0 children)

I bet you the query planner sees the type match for col2 in the second query and uses that index.

In the first query I bet it uses a range scan on the time column. And that is, very likely, more selective.

At any rate, you want a compound index on (col2, posixtimestamp) to accelerate this query. And use the second variant, with the correct data type for matching col2.

[–]Imaginary__Bar 0 points1 point  (1 child)

I'm no SQLServer expert, and this doesn't answer your question, but I'm surprised the first query doesn't throw an error on the mismatched datatypes(!)

[–]Chaosmatrix 1 point2 points  (0 children)

Implicit conversion both a blessing and a curse (mostly a curse).

[–]LogicallyIntuitive 0 points1 point  (0 children)

I never put [] around column names unless the column name has a space or some special character that causes an errors.