Suppose I have a table, Document, that looks something like this:
_______________________
| Document |
|-----------------------|
| DocumentId int PK |
| (add't fields) |
|_______________________|
Now suppose I have a second table:
_______________________
| DocumentVersion |
|-----------------------|
| DocumentId int PK, FK |
| VersionId int PK |
| (add't fields) |
|_______________________|
Finally, suppose I wish to create a third table that references DocumentVersion, perhaps an audit of users that have accessed each version (assume a User table exists):
_______________________
| VersionAccessLog |
|-----------------------|
| DocumentId int PK, FK |
| VersionId int PK, FK |
| UserId int PK, FK |
| AccessTime DateTime PK|
|_______________________|
Maybe not the best example but hopefully enough to illustrate my question.
Focusing on VersionAccessLog, we have:
- PK(DocumentId, VersionId, UserId, AccessTime)
- FK(DocumentId, VersionId) REFERENCES DocumentVersion
- FK(userId) REFERENCES User
Now my question is, should I also in VersionAccessLog create a FK(DocumentId)? At first glance, the key seems superfluous– referential integrity is enforced by the FK to DocumentVersion. However, from a relational algebra standpoint, should this key exist or not? From a practical standpoint (assume SQL Server 2012 if necessary), are there any performance implications of including or excluding the key?
There are performance impacts to including the additional key, because the database will check the FK on every insert (child) or delete(parent). From a practical perspective, I generally do not include the extra keys because there really isn’t any value in the validations and there is the slight performance cost.
I would make sure that if the schema was ever changed and the FK between DocumentVersion and VersionAccessLog was removed, to add the FK between VersionAccessLog and Document. The only other time I could see adding it is if some Schema aware DAO library was used that reverses Has-a relationships from FK’s, and it was worthwhile to include that.