1

I have a table with (ID, col1, col2) & query of

SELECT ID FROM table WHERE col1 = 2
AND col2 = 7

Should I create a composite index

CREATE NONCLUSTERED INDEX IDX_Composite ON table (ID, col1, col2)

or covering index

CREATE NONCLUSTERED INDEX IDX_Covering ON table ID INCLUDED (col1, col2)
3
  • FYI, if you have 2 questions, please post 2 question, unless the 2 are very closely related. These don't appear to be. Commented Jun 29, 2022 at 14:59
  • In regards to the index creation, the one that would help the data engine the most would be one on col1 and col2 with ID INCLUDEd; which neither of your indexes are. An index which is ordered on ID first is going to require a full scan for that query. Commented Jun 29, 2022 at 15:01
  • I would also recommend (col1, col2) INCLUDE (ID) although note that if ID is the clustering key it will be included anyway Commented Jun 29, 2022 at 15:02

1 Answer 1

1

Neither of the indexes in your question will help the query you have. The reason for this is because the first sorting column is the ID, however, your filtering columns are on col1 and col2; as such the index doesn't help the data engine quickly seek to the rows you need.

Let's put what you have into a classic phone book analogy. Let's say that the ID is the Phone Number, Col1 the Surname, and Col2 the Forename. If we use your index, the phone phone book is order by phone number, starting at the "lowest" phone number and ending at the "highest". If you want phone numbers for people called "John Smith" your only option is to go through the entire book and find every John Smith.

A traditional phone book, however, is ordered by the Surname, then Forename, and has the phone number for each beside them. This means that you can now easily service the question of "What are the phone numbers for John Smith"? Flick through the book to "Smith" first, then "John", and you have all the phone numbers.

So, what your index should look like is the following:

CREATE NONCLUSTERED INDEX IX_Composite ON table (col1, col2) INCLUDE (ID);

As noted by Charlieface as well, if your column ID is your clustered index then there is actually no need to INCLUDE it; the column(s) in the clustered index are automatically INCLUDEd in any NONCLUSTERED indexes.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your information. I understand for the way using covering index now. Can I know when can we use composite index instead of covering index?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.