Question

We're designing a database in which I need to consider some FK(foreign key) constraints. But it is not limited to formal structuring and normalization. We go for it only if it provides any performance or scalability benefits.

I've been going thru some interesting articles and googling for practical benefits. Here are some links:

http://www.mssqltips.com/tip.asp?tip=1296

I wanted to know more about the benefits of FK (apart from the formal structuring and the famous cascaded delete\update).

  • FK are not 'indexed' by default so what are the considerations while indexing an FK?

  • How to handle nullable fields which are mapped as foreign key - is this allowed?

  • Apart from indexing, does this help in optimizing query-execution plans in SQL-Server?

I know there's more but I'd prefer experts speaking on this. Please guide me.

Was it helpful?

Solution

  • Foreign keys provide no performance or scalability benefits.
  • Foreign keys enforce referential integrity. This can provide a practical benefit by raising an error if someone attempted to delete rows from the parent table in error.
  • Foreign keys are not indexed by default. You should index your foreign keys columns, as this avoids a table scan on the child table when you delete/update your parent row.
  • You can make a foreign key column nullable and insert null.

OTHER TIPS

The main benefit is that your database will not end up inconsistent if your buggy client code tries to do something wrong. Foreign keys are a type of 'constraint', so that's how you should use them.

They do not have any "functional" benefit, they will not optimize anything. You still have to create indexes yourself, etc. And yes, you can have NULL values in a column that is a foreign key.

FK constraints keep your data consistent. That's it. This is the main benefit. FK constraints will not provide you with any performance gain.

But, unless you have denormalized on purpose db structure, I'd recommend you to use FK constraints. The main reason - consistency.

I have read at least one example on net where it was shown that Foreign Keys do improve performance because the optimiser does not have to do additional checks across tables because it knows data meets certain criteria already due to the FK. Sorry I don't have a link but the blog gave detailed output of the query plans to prove it.

As mentioned, they are for data integrity. Any performance "loss" would be utterly wiped out by the time required to fix broken data.

However, there could be an indirect performance benefit.

For SQL Server at least, the columns in the FK must have the same datatype on each side. Without an FK, you could have an nvarchar parent and a varchar child for example. When you join the 2 tables, you'll get a datatype conversions which can kill performance.

Example: different varchar lengths causing an issue

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top