I am not an expert in optimizing SQL Server internal processes / queries, but here are my 2 pence (or cents, if you prefer).
I believe this is due to the use of the ROW_NUMBER () value in the WHERE clause. As an example, I created an example table filled with 1000 rows from ID 1 to 1000 (identifier as primary key), as you said.
If you select ROW_NUMBER () and execute a query based on the ID column, for example:
Select * FROM ( SELECT ID, Name FROM Log ) as LogWithRowNumbers WHERE ID>=1 and ID<=2
Then it correctly shows the number of rows as 2 - as expected.
Now, working backwards, add ROW_NUMBER to the inner SELECT, but leave the WHERE clause as if:
Select * FROM ( SELECT ROW_NUMBER() OVER (ORDER BY ID DESC) AS RowNo, ID, Name FROM Log ) as LogWithRowNumbers WHERE ID>=1 AND ID <=2
This still shows the correct number of rows as 2.
Finally, set the WHERE clause to use RowNo as the column that is filtered instead of ID, this is when the counted number of rows moves to 9.
Therefore, I believe that this is using the ROW_NUMBER () function, which is filtered in the WHERE clause, which is the reason. Therefore, I would have imagined it because the actual columns of the table obviously have better / more accurate statistics than with this expression created by the function.
I hope this is at least a good starting point, hope it will be helpful!
Adathedev
source share