foreign key and index issue

浪尽此生 提交于 2019-12-10 11:18:10

问题


I am using SQL Server 2008 Enterprise. I have a table and one of its column is referring to another column in another table (in the same database) as foreign key, here is the related SQL statement, in more details, column [AnotherID] in table [Foo] refers to another table [Goo]'s column [GID] as foreign key. [GID] is primary key and clustered index on table [Goo].

My question is, in this way, if I do not create index on [AnotherID] column on [Foo] explicitly, will there be an index created automatically for [AnotherID] column on [Foo] -- because its foreign key reference column [GID] on table [Goo] already has primary clustered key index?

CREATE TABLE [dbo].[Foo](
    [ID] [bigint] IDENTITY(1,1) NOT NULL,
    [AnotherID] [int] NULL,
    [InsertTime] [datetime] NULL CONSTRAINT DEFAULT (getdate()),
 CONSTRAINT [PK_Foo] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

ALTER TABLE [dbo].[Foo]  WITH CHECK ADD  CONSTRAINT [FK_Foo] FOREIGN KEY([Goo])
REFERENCES [dbo].[Goo] ([GID])
ALTER TABLE [dbo].[Foo] CHECK CONSTRAINT [FK_Foo]

thanks in advance, George


回答1:


No. SQL Server does not and never has automatically created indices on foreign key columns. It's a wide spread urban myth - but it's nothing more than that - a myth.

But it's an accepted best practice to do so - so that's one of the most basic recommendations for index tuning - put indices on your foreign key columns.

See Kimberly Tripp's excellent When did SQL Server stop putting indexes on foreign key columns? blog post for more background info.




回答2:


No, there will not be an index created, you have to do it yourself



来源:https://stackoverflow.com/questions/2979819/foreign-key-and-index-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!