Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should every SQL Server foreign key have a matching index?

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

like image 207
GRGodoi Avatar asked Sep 06 '10 10:09

GRGodoi


People also ask

Should every foreign key have an index?

It is highly recommended to create an index on each foreign key constraint on the child table, as it is very common when calling that key on your queries to join between the child table and the parent table columns, providing better joining performance.

Does SQL Server automatically index foreign keys?

SQL Server will not automatically create an index on a foreign key. Also from MSDN: A FOREIGN KEY constraint does not have to be linked only to a PRIMARY KEY constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table.

Should a foreign key always have the same value as the primary key?

Since each foreign key value must exactly match the corresponding primary key value, the foreign key must contain the same number and data type of columns as the primary key, and these key columns must be in the same order. A foreign key can also have different column names than the primary key.

Does a foreign key have to match a primary key?

Practically, the foreign key has nothing to do with the primary key tag of another table, if it points to a unique column (not necessarily a primary key) of another table then too, it would be a foreign key.


2 Answers

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

like image 142
SQLMenace Avatar answered Oct 19 '22 09:10

SQLMenace


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.

like image 34
onedaywhen Avatar answered Oct 19 '22 09:10

onedaywhen