sql-server

Does a foreign key automatically create an index?


I've been told that if I foreign key two tables, that SQL Server will create something akin to an index in the child table. I have a hard time believing this to be true, but can't find much out there related specifically to this.

My real reason for asking this is because we're experiencing some very slow response time in a delete statement against a table that has probably 15 related tables. I've asked our database guy and he says that if there is a foreign key on the fields, then it acts like an index. What is your experience with this? Should I add indexes on all foreign key fields or are they just unnecessary overhead?


Solution

  • A foreign key is a constraint, a relationship between two tables - that has nothing to do with an index per se.

    However, it makes a lot of sense to index all the columns that are part of any foreign key relationship. An FK-relationship will often need to look up a relating table and extract certain rows based on a single value or a range of values.

    So it makes good sense to index any columns involved in an FK, but an FK per se is not an index.

    Check out Kimberly Tripp's excellent article "When did SQL Server stop putting indexes on Foreign Key columns?".

    Updated 5/31/2023
    For those reading this now, I (the original poster) wanted to update Marc's excellent answer to point out that Entity Framework Core now auto generates indexes for foreign keys discovered by convention. Most helpful. Not sure how far back that feature exists, I'm using EF Core 7.