Should I have a dedicated primary key field?

后端 未结 11 1653
温柔的废话
温柔的废话 2020-11-30 10:05

I\'m designing a small SQL database to be used by a web application.

Let\'s say a particular table has a Name field for which no two rows will be allowed to have the

11条回答
  •  既然无缘
    2020-11-30 10:31

    The primary key for a record must be unique and permanent. If a record naturally has a simple key which fulfills both of those, then use it. However, they don't come around very often. For a person record, the person's name is neither unique nor permanent, so you pretty much have to use a auto-increment.

    The one place where natural keys do work is on a code table, for example, a table mapping a status value to its description. There is little sense to give "Active" a primary key of 1, "Delay" a primary key of 2, etc. When it is just as easy to give "Active" a primary key of "ACT"; "Delayed", "DLY"; "On Hold", "HLD" and so on.

    Note also, some say you should use integers over strings because they compare faster. Not really true. A comparing two 4-byte character fields will take exactly as long as comparing two 4-byte integer fields. Longer string will, of course take longer, but if you keep the codes short, there's no difference.

提交回复
热议问题