Are foreign keys indexed automatically in SQL Server?

前端 未结 3 457
忘了有多久
忘了有多久 2020-12-08 00:18

Would the following SQL statement automatically create an index on Table1.Table1Column, or must one be explicitly created?

Database engine is SQL Server 2000

3条回答
  •  不知归路
    2020-12-08 00:19

    No, creating a foreign key on a column does not automatically create an index on that column. Failing to index a foreign key column will cause a table scan in each of the following situations:

    • Each time a record is deleted from the referenced (parent) table.
    • Each time the two tables are joined on the foreign key.
    • Each time the FK column is updated.

    In this example schema:

    CREATE TABLE MasterOrder (
       MasterOrderID INT PRIMARY KEY)
    
    CREATE TABLE OrderDetail(
       OrderDetailID INT,
       MasterOrderID INT  FOREIGN KEY REFERENCES MasterOrder(MasterOrderID)
    )
    

    OrderDetail will be scanned each time a record is deleted in the MasterOrder table. The entire OrderDetail table will also be scanned each time you join OrderMaster and OrderDetail.

       SELECT ..
       FROM 
          MasterOrder ord
          LEFT JOIN OrderDetail det
           ON det.MasterOrderID = ord.MasterOrderID
       WHERE ord.OrderMasterID = @OrderMasterID
    

    In general not indexing a foreign key is much more the exception than the rule.

    A case for not indexing a foreign key is where it would never be utilized. This would make the server's overhead of maintaining it unnecessary. Type tables may fall into this category from time to time, an example might be:

    CREATE TABLE CarType (
       CarTypeID INT PRIMARY KEY,
       CarTypeName VARCHAR(25)
    )
    
    INSERT CarType .. VALUES(1,'SEDAN')
    INSERT CarType .. VALUES(2,'COUP')
    INSERT CarType .. VALUES(3,'CONVERTABLE')
    
    CREATE TABLE CarInventory (
       CarInventoryID INT,
       CarTypeID INT  FOREIGN KEY REFERENCES CarType(CarTypeID)
    )
    

    Making the general assumption that the CarType.CarTypeID field is never going to be updated and deleting records would be almost never, the server overhead of maintaing an index on CarInventory.CarTypeID would be unnecessary if CarInventory was never searched by CarTypeID.

提交回复
热议问题