Why is my SQL Server ORDER BY slow despite the ordered column being indexed?

后端 未结 5 2267
一整个雨季
一整个雨季 2020-12-29 06:13

I have an SQL query (generated by LINQ to Entities) which is roughly like the following:

SELECT * FROM [mydb].[dbo].[employees]
JOIN [mydb].[dbo].[industry]
         


        
5条回答
  •  难免孤独
    2020-12-29 06:33

    Because your query projects all the columns (*), it needs 5 columns for the join conditions and has an unselective WHERE clause on what is likely a joined table column, it causes it to hit the Index Tipping Point: the optimizer decides that it is less costly to scan the entire table, filter it and sort it that it would be to range scan the index and then lookup each key in the table to retrieve the needed extra columns (the 5 for the joins and the rest for the *).

    A better index to partially cover this query could be:

    CREATE INDEX ... ON .. (countryId, startDatetime);
    

    Jeffrey's suggestion to make the clustered index would cover the query 100% and would definitely improve performance, but changing the clustered index has many side effects. I would start with a non-clustered index as above. Unless they are needed by other queries, you can drop all the other non-clustered indexes you created, they won't help this query.

提交回复
热议问题