Skip to content
Advertisement

Is there a severe performance hit for using Foreign Keys in SQL Server?

I’m trying my best to persuade my boss into letting us use foreign keys in our databases – so far without luck.

He claims it costs a significant amount of performance, and says we’ll just have jobs to cleanup the invalid references now and then.

Obviously this doesn’t work in practice, and the database is flooded with invalid references.

Does anyone know of a comparison, benchmark or similar which proves there’s no significant performance hit to using foreign keys? (Which I hope will convince him)

Advertisement

Answer

There is a tiny performance hit on inserts, updates and deletes because the FK has to be checked. For an individual record this would normally be so slight as to be unnoticeable unless you start having a ridiculous number of FKs associated to the table (Clearly it takes longer to check 100 other tables than 2). This is a good thing not a bad thing as databases without integrity are untrustworthy and thus useless. You should not trade integrity for speed. That performance hit is usually offset by the better ability to optimize execution plans.

We have a medium sized database with around 9 million records and FKs everywhere they should be and rarely notice a performance hit (except on one badly designed table that has well over 100 foreign keys, it is a bit slow to delete records from this as all must be checked). Almost every dba I know of who deals with large, terabyte sized databases and a true need for high performance on large data sets insists on foreign key constraints because integrity is key to any database. If the people with terabyte-sized databases can afford the very small performance hit, then so can you.

FKs are not automatically indexed and if they are not indexed this can cause performance problems.

Honestly, I’d take a copy of your database, add properly indexed FKs and show the time difference to insert, delete, update and select from those tables in comparision with the same from your database without the FKs. Show that you won’t be causing a performance hit. Then show the results of queries that show orphaned records that no longer have meaning because the PK they are related to no longer exists. It is especially effective to show this for tables which contain financial information (“We have 2700 orders that we can’t associate with a customer” will make management sit up and take notice).

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement