views:

27

answers:

2

Hello everyone,

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

+2  A: 

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.

marc_s
1. Marc, sorry my English is not good. You mean there is no index created for [AnotherID] column for table [Foo], correct? 2. So, if I access table [Foo] by using [AnotherID] frequently, it will be very inefficient, correct?
George2
@George2: Correct on both counts.
Piskvor
@George2: yes, exactly: by default, SQL Server does **NOT** create an index on Foo.AnotherID, and yes, having an index can make certain operations (joins, lookups) a lot faster.
marc_s
Marc, you cool! Question answered!
George2
+2  A: 

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

SQLMenace
So, if I access table [Foo] by using [AnotherID] frequently, it will be very inefficient, correct?
George2
If you want to know for sure without believing people from the internets I would say take a look at the execution plan
SQLMenace

related questions