Better to use a Clustered index or a Non-Clustered index with included columns?

后端 未结 3 1559
北荒
北荒 2021-01-13 16:25

When I look at the execution plan for a particular query I find that 77% of my cost is in a Clustered Index seek.

Does the fact that I\'m using a clustered index m

相关标签:
3条回答
  • 2021-01-13 16:58

    The reason you use include columns on a non-clustered index is to avoid "bookmark-lookups" into the clustered data. The thing is that if SQL Server could theoretically use a particular non-clustered index but the Optimiser estimates there will be 'too many' bookmark-lookups then said index will be ignored. However, if all selected columns are accessible directly from the index, there'll be no need for a bookmark-lookup.

    In your case the fact that you're accessing the data via "clustered index seek" is very promising. It will be very hard to improve on its performance. A non-clustered index including all selected columns may be slightly faster, but only because the raw data is a little less. (But don't forget the cost of increased insert/update time.)

    However, you should check the detail...

    • If you're using a composite key and the seek is actually only on the beginning of the key, you might not be so lucky. You may find the seek is only narrowing down to 500,000 rows and is then searching that based on other criteria. In this case experiment with some non-clustered indexes.
    • The clustered index seek itself may be fine; but if it is being done 100,000 times in your query because some other aspect is inefficiently returning too many rows - then you won't gain much by improving the performance of the clustered index seek.

    Finally, to elaborate on davek's comment: "cost is relative". Just because the clustered is 77% of your query cost doesn't mean there's a problem. It is possible to write a trivial 1 table query that returns a sinlge row and clustered index seek cost at 100%. (But of course, being the only 'work' done, it will be 100% of the work... and 100% of instant is still instant.
    So: "Don't worry; be happy!"

    0 讨论(0)
  • 2021-01-13 17:05

    You have a seek already, so benefits may be minimal.

    You can try it though. Options:

    • 2nd non-clustered index, keep original
    • move clustered index to another column(s)

    Are there other good cluster candidates? Note, you always need a unique clustered index (because of uniquifiers + here SO + here). And of course, what is your PK please?

    0 讨论(0)
  • 2021-01-13 17:08

    It depends on how many columns you are talking about, if a couple then yes, a non clustered index will perform better, if you are selecting most of the columns the clustered index is better.

    0 讨论(0)
提交回复
热议问题