开发者

SQL Server, is this correct index usage?

开发者 https://www.devze.com 2023-02-27 17:48 出处:网络
I\'m trying to get to grips with indexes.Given the table: Books ------ ID (PK) Title CategoryID (FK) AuthorID (FK)

I'm trying to get to grips with indexes. Given the table:

Books
------
ID (PK)
Title
CategoryID (FK)
AuthorID (FK)

Where in my ASP.net pages, I have webpages that will fetch the books by author, or by category, would I create an index on C开发者_如何学CategoryID Asc, AuthorID asc if I wanted to improve retrieval times?

Have I correctly understood it? If I use multiple columns as above, is that called a clustered index or is that something else?


You should create two indexes, one for the CategoryID and one for the AuthorID. Having both in the same index is not what you need if you look for one or the other; you'd need that if you were always querying for both at the same time (e.g. category and author).

A clustered index controls the physical order of the data. Usually, if you have an identity column, using it as clustered index (which the primary key by default is) is just fine.


A clustered index means the data is stored in the table and on disk (etc.) in the order the index specifies. A consequence of this is, that only one clustered index can exist.

The index CategoryID Asc, AuthorID asc will make lookups on specific categories faster, and lookups on specific categories with specific authors would be ideal. But it is not ideal for author lookups alone because you will have to find authors for every category. In that case two separate indexes would be better.


The appropriate index would depends on what the query does. If you have a query joining against both category and author, then you may have use for an index with both fields, otherwise you may have more use for two separate indexes.

A clustered index is an index that decides the storage order of the records in the table, and has nothing to do with the number of fields it contains. You should already have a clustered index on the primary key, so you can't create another clustered index for that table.

0

精彩评论

暂无评论...
验证码 换一张
取 消