84

What are the advantages, if any exist, of having an an index for every foreign key in a SQL Server database?

Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
GRGodoi
  • 1,946
  • 2
  • 24
  • 38

4 Answers4

65

Yes it's a good practice, see here: When did SQL Server stop putting indexes on Foreign Key columns? scroll down to the Are there any benefits to indexing foreign key columns? section

Rich O'Kelly
  • 41,274
  • 9
  • 83
  • 114
SQLMenace
  • 132,095
  • 25
  • 206
  • 225
61

Every foreign key? No. Where the selectivity is low (i.e. many values are duplicated), an index may be more costly than a table scan. Also, in a high activity environment (much more insert/update/delete activity than querying) the cost of maintaining the indexes may affect the overall performance of the system.

onedaywhen
  • 55,269
  • 12
  • 100
  • 138
25

The reason for indexing a foreign key column is the same as the reason for indexing any other column: create an index if you are going to filter rows by the column.

For example, if you have table [User] (ID int, Name varchar(50)) and table [UserAction] (UserID int, Action varchar(50)) you will most probably want to be able to find what actions a particular user did. For example, you are going to run the following query:

select ActionName from [UserAction] where UserID = @UserID

If you do not intend to filter rows by the column then there is no need to put an index on it. And even if you do it's worth it only if you have more than 20 - 30 rows.

ItsMe
  • 271
  • 3
  • 2
  • 3
    Are you sure that the index will not be useful during the foreign key validation when I execute an insert on UserAction? – GRGodoi Nov 08 '12 at 01:51
  • 1
    No. The validation is done against the table and column that holds the primary key or unique constraint (e.g. [User].[ID]). There is no need to validate the UserID column of the [UserAction] table. You can only reference a column that has primary key or unique constraint on it so it is always indexed. – ItsMe Nov 19 '12 at 02:38
  • 10
    The other action to consider is deleting rows from `User`, which causes the engine to look for rows in `UserAction` based on `UserID`. – T.J. Crowder Jul 27 '15 at 06:12
7

From MSDN: FOREIGN KEY Constraints

Creating an index on a foreign key is often useful for the following reasons:

  • Changes to PRIMARY KEY constraints are checked with FOREIGN KEY constraints in related tables.
  • Foreign key columns are frequently used in join criteria when the data from related tables is combined in queries by matching the column or columns in the FOREIGN KEY constraint of one table with the primary or unique key column or columns in the other table.
Serghei Belyi
  • 71
  • 1
  • 5