简体   繁体   中英

Composite clustered index and non clustered index in sql server 2005

I created a new table with composite primary key, Lets say PrmID and Type, therefor a new composite clustered index has created (PrmID is first).I add another non clustered index for Type.

My question is - when I generate a queries that perform any statement on Type (such as GROUP BY), is the SQL engine using the non clustered index table or the PK clustered index (which more expensive for that kind of queries) ?

-- EDIT --

Thanks marc, I missed that...

-- END EDIT --

Second, is PrimID really not unique in your table, and is only unique in combination with Type? If PrimID is not duplicated in the table, maybe reconsider making it a composite PK.

Third, the best way to answer these types of questions is to look at the execution plan for your query. We can give you an answer on how we think SQL should handle the plan, but SQL Server will change the execution plan for various circumstances based on the data in your database, your hardware, etc...

Here's what the execution plan will look like: 在此处输入图片说明

You can see that it tells you excatly which idexes are used, and how they are used... here's an article that gives a good introduction into understanding the execution plans.

It depends on what the query look like, what columns are accessed, is it covering etc

A simple GROUP BY on type will most likely use the NC index. If you use other columns you may get a bookmap/key lookup or the index will be ignored and you'll have an inefficient PK scan

My understanding is that when you have a multi-field index and your query is not using the first field in the index, then that index will not be used (too difficult, not efficient, etc.) It will then use the other index.

But, to know this definitely , run your query with an execution plan, or even just an estimated execution plan. If you are using SSMS this is easy as pressing a tool bar button. It is the one that looks like three little blue and green boxes in an inverted "L" pattern. This will tell you exactly what index is being used. And while execution plans can change over the life of a query (as the data changes), it should not for this answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM