in general, should every table in a database have an identity field to use as a PK?

前端 未结 10 1912
旧时难觅i
旧时难觅i 2020-12-07 15:36

This seems like a duplicate even as I ask it, but I searched and didn\'t find it. It seems like a good question for SO -- even though I\'m sure I can find it on many blogs e

10条回答
  •  半阙折子戏
    2020-12-07 16:07

    I'm a firm believer that natural keys are often far worse than artificial keys because you often have no control over whether they will change which can cause horrendous data integrity or performance problems.

    However, there are some (very few) natural keys that make sense without being an identity field (two-letter state abbreviation comes to mind, it is extremely rare for these official type abbreviations to change.)

    Any table which is a join table to model a many to many relationship probably also does not need an additional identity field. Making the two key fields together the primary key will work just fine.

    Other than that I would, in general, add an identity field to most other tables unless given a compelling reason in that particular case not to. It is a bad practice to fail to create a primary key on a table or if you are using surrogate keys to fail to place a unique index on the other fields needed to guarantee uniqueness where possible (unless you really enjoy resolving duplicates).

提交回复
热议问题