What's the best practice for primary keys in tables?

前端 未结 21 2239
别那么骄傲
别那么骄傲 2020-11-22 14:02

When designing tables, I\'ve developed a habit of having one column that is unique and that I make the primary key. This is achieved in three ways depending on requirements

21条回答
  •  忘了有多久
    2020-11-22 14:06

    Natural verses artifical keys is a kind of religious debate among the database community - see this article and others it links to. I'm neither in favour of always having artifical keys, nor of never having them. I would decide on a case-by-case basis, for example:

    • US States: I'd go for state_code ('TX' for Texas etc.), rather than state_id=1 for Texas
    • Employees: I'd usually create an artifical employee_id, because it's hard to find anything else that works. SSN or equivalent may work, but there could be issues like a new joiner who hasn't supplied his/her SSN yet.
    • Employee Salary History: (employee_id, start_date). I would not create an artifical employee_salary_history_id. What point would it serve (other than "foolish consistency")

    Wherever artificial keys are used, you should always also declare unique constraints on the natural keys. For example, use state_id if you must, but then you'd better declare a unique constraint on state_code, otherwise you are sure to eventually end up with:

    state_id    state_code   state_name
    137         TX           Texas
    ...         ...          ...
    249         TX           Texas
    

提交回复
热议问题