Native primary key or auto generated one?

廉价感情. 提交于 2019-11-29 11:03:26

A primary key

  1. must identify a row uniquely.
  2. must not contain data, or it will change when your data changes (which is bad)
  3. should be fast in comparing operations (WHERE clauses / joins)

Ideally, you use an artificial (surrogate) key for your rows, a numeric integer data type (INT) is best, because space-efficient and fast.

A primary key should be made of the minimum number of fields to still fulfill conditions 1.-3. For vast majority of tables this minimum is: 1 field.

For relation tables (or very special edge cases), it may be higher. Referencing a table with a composite primary key is cumbersome, so a composite key is not recommended for a table that must be referenced on it's own.

In relation tables (m:n relations) you make a composite key out of the primary keys of the related tables, hence your composite key automatically fulfills all three conditions from above.

You could make primary keys out of data if you are absolutely sure, that it will be unique and will never change. Since this is hard to guarantee, I'd recommend against it.

Always ints.

You'll appreciate you did so when it's time to cross reference those elements in other tables (using foreign keys)

Whatever it is, make it non meaningful (surrogate key). Meaningful primary keys are deadly.

It is an old war between purists and pragmatists. Purists don't accept surrogate primary keys and insist on using only natural ones. If you ask me, I'll vote for increment (surrogate keys) in most of situations.

I would say auto generating, theres no real reason not to in my mind. Unless your developing some kind of hash table, but even so, I would stick to a unique primary key automatically created by the database. Its quick, simple and reliable. Don't reinvent the wheel if its already there.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!