Pros and Cons of autoincrement keys on “every table”

前端 未结 9 741
误落风尘
误落风尘 2020-12-09 12:54

We are having a rather long discussion in our company about whether or not to put an autoincrement key on EVERY table in our database.

I can understand putting one o

相关标签:
9条回答
  • 2020-12-09 13:25

    Many tables are better off with a compound PK, composed of two or more FKs. These tables correspond to relationships in the Entity-Relationship (ER) model. The ER model is useful for conceptualizing a schema and understanding the requirements, but it should not be confused with a database design.

    The tables that represent entities from an ER model should have a smiple PK. You use a surrogate PK when none of the natural keys can be trusted. The decision about whether a key can be trusted or not is not a technical decision. It depends on the data you are going to be given, and what you are expected to do with it.

    If you use a surrogate key that's autoincremented, you now have to make sure that duplicate references to the same entity don't creep into your databases. These duplicates would show up as two or more rows with a distinct PK (because it's been autoincremented), but otherwise duplicates of each other.

    If you let duplicates into your database, eventually your use of the data is going to be a mess.

    0 讨论(0)
  • 2020-12-09 13:26

    You need primary keys on these tables. You just don't know it yet.

    0 讨论(0)
  • 2020-12-09 13:28

    Consider this:

    A record is deleted in one table that has a relationship with another table. The corresponding record in the second table cannot be deleted for auditing reasons. This record becomes orphaned from the first table. If a new record is inserted into the first table, and a sequential primary key is used, this record is now linked to the orphan. Obviously, this is bad. By using an auto incremented PK, an id that has never been used before is always guaranteed. This means that orphans remain orphans, which is correct.

    I would never use natural keys as a PK. A numeric PK, like an auto increment is the ideal choice the majority of the time, because it can be indexed efficiently. Auto increments are guaranteed to be unique, even when records are deleted, creating trusted data relationships.

    0 讨论(0)
提交回复
热议问题