Native primary key or auto generated one?

后端 未结 6 1432
无人共我
无人共我 2020-12-19 11:38

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?

6条回答
  •  醉话见心
    2020-12-19 12:05

    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.

提交回复
热议问题