Does specifying a foreign key make it an index?

前端 未结 3 662
无人及你
无人及你 2021-01-14 10:01

I have a table T with a primary key id and foreign key f. Is f automatically indexed when it is specified as a foreign key? Do I need explicitly add an index for f ?

相关标签:
3条回答
  • 2021-01-14 10:17

    No, it is a constraint, not an index.

    see Are foreign keys indexed automatically in SQL Server?

    0 讨论(0)
  • 2021-01-14 10:25

    No index is created so yes, you need add explicitly add an index.

    Edited to add... I probably ought to add that the source table/column for the data in table T must have a unique index. If you try and make an FK to a column that isn't a unique index (either as a PK or with a UNIQUE constraint), the FK can't be created.

    0 讨论(0)
  • 2021-01-14 10:27

    In case of the foreign key constraint, the foreign key f in table T would be a primary key in the referenced table say T2. In SQL Server a clustered index would be automatically created when T2 got created.

    cheers

    0 讨论(0)
提交回复
热议问题