Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
921 views
in Technique[技术] by (71.8m points)

database - Native primary key or auto generated one?

As a rule is it better to use native primary keys (ie existing columns or combination of columns) or set your primary key to an auto generating row of integers?

EDIT:
It has been pointed out to me that this very similar to this question.

The consensus here is to use surrogate keys, which was my natural inclination, but my boss told me I should also use natural keys where possible. His advice may be best for this particular application, as Name in row uniquely identifies it and we have a need to maintain the ability to view old data, thus any changes to the name/rule is going to mean new unique row.

While the answers here are all helpful, most of them are based on the subjective "here is what you should", and do not cite supporting sources. Am I missing some essential reading or are the best practices database design highly subjective and/or application dependent?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...