Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pros and Cons of autoincrement keys on "every table"

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 on tables that would have a FK reference to, but I kind-of dislike putting such keys on each and every one of our tables, even though the keys would never be used.

Please help with pros and cons for putting autoincrement keys on every table apart from taking extra space and slowing everything a little bit (we have some tables with hundreds of millions of records).

Thanks

like image 963
Brumbar Avatar asked Jan 04 '10 03:01

Brumbar


1 Answers

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.

like image 188
KenFar Avatar answered Nov 02 '22 03:11

KenFar