Pros and Cons of autoincrement keys on “every table”

前端 未结 9 773
误落风尘
误落风尘 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

    I'm assuming that almost all tables will have a primary key - and it's just a question of whether that key consists of one or more natural keys or a single auto-incrementing surrogate key. If you aren't using primary keys then you will generally get a lot of advantages of using them on almost all tables.

    So, here are some pros & cons of surrogate keys. First off, the pros:

    • Most importantly: they allow the natural keys to change. Trivial example, a table of persons should have a primary key of person_id rather than last_name, first_name.
    • Read performance - very small indexes are faster to scan. However, this is only helpful if you're actually constraining your query by the surrogate key. So, good for lookup tables, not so good for primary tables.
    • Simplicity - if named appropriately, it makes the database easy to learn & use.
    • Capacity - if you're designing something like a data warehouse fact table - surrogate keys on your dimensions allow you to keep a very narrow fact table - which results in huge capacity improvements.

    And cons:

    • They don't prevent duplicates of the natural values. So, you'll still usually want a unique constraint (index) on the logical key.
    • Write performance. With an extra index you're going to slow down inserts, updates and deletes that much more.
    • Simplicity - for small tables of data that almost never changes they are unnecessary. For example, if you need a list of countries you can use the ISO list of countries. It includes meaningful abbreviations. This is better than a surrogate key because it's both small and useful.

    In general, surrogate keys are useful, just keep in mind the cons and don't hesitate to use natural keys when appropriate.

提交回复
热议问题