Imagine a database that tracks payments between customers.
Say I’ve got a Customer table:
Customer
----------
CustomerID
Name
and a Transaction table
Transaction
------------
BuyerID
SellerID
Amount
Where BuyerID and SellerID are both Foreign Key references to the CustomerID column of the Customer table.
In my current (analogous) situation, the Transaction table is large (500 Million Rows), even though the Customer table is small (2000 rows). Deleting a row from the Customer table, however, takes a very long time, because the database has to scan the Transaction table to see whether the Customer has any referencing Transactions (In fact, it has to do it twice – one to check for BuyerID and one for SellerID). The Transaction table is not Indexed on either BuyerID or SellerID (The real table is indexed on a combination of Buyer, Seller, and a few other columns)
I know I can drop all the foreign key constraints, delete the rows, and then re-add the constraints. Will that be any faster than just doing the DELETE FROM with the foreign keys enabled? Are there any other ways to speed up the delete operation that I’m missing.
You should index
BuyerIDandSellerIDin yourTransactiontable…For a further explanation as to why you should be indexing your foreign keys, read Kimberly Tripp’s excellent article on the subject.