开发者

In SQL Server, should I create an index for an identity column, or is it created automatically?

开发者 https://www.devze.com 2023-01-28 20:50 出处:网络
I believe when I create an identity column it gets indexed automatically, but I\'m not 100% sure. Should I c开发者_开发技巧reate an index for an identity column, or is it created automatically?create

I believe when I create an identity column it gets indexed automatically, but I'm not 100% sure.

Should I c开发者_开发技巧reate an index for an identity column, or is it created automatically?


create table test (Id int identity)
go
sp_help test

The object 'test' does not have any indexes, or you do not have permissions.

No constraints are defined on object 'test', or you do not have permissions.

As a general practice you would create a unique index on your identity column, this speeds up lookups.

Usually you would like your identity columns to be 'clustered indexes' as well (Id int identity primary key is the shortcut notation), meaning table is layed out on disk in the same order your identity column is. This optimizes for inserts, as the page being inserted into tends to be in memory. In some cases, when you are doing ranged lookups very frequently on other data in the table, you may consider clustering other columns instead, as SQL Server only allows you one clustered index per table.


If you create a column with a PRIMARY KEY constraint, a clustered index will be created by default (assuming this is a new table and no such index is already defined).

Being an IDENTITY field has nothing to do with it.

So, to answer you question - if you are going to query/sort with this field and it is not a primary key, you should define an index on it (rule of thumb, always test for your scenario).


By default, your primary key column(s) will be made into a clustered index; this is a special index that is not separate from the data - but instead, the data is ordered in the table by that indexes values.

I say 'by default', because you can change the clustered index to another field if you wanted. If you've chosen a good identity value for your primary key, you will almost never want to change this, though.

0

精彩评论

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

关注公众号