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

前端 未结 21 2236
别那么骄傲
别那么骄傲 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:13

    Here are my own rule of thumbs I have settled on after 25+ years of development experience.

    • All tables should have a single column primary key that auto increments.
    • Include it in any view that is meant to be updateable
    • The primary key should not have any meaning in the context of your application. This means that it should not be a SKU, or an account number or an employee id or any other information that is meaningful to your application. It is merely a unique key associated with an entity.

    The primary key is used by the database for optimization purposes and should not be used by your application for anything more than identifying a particular entity or relating to a particular entity.

    Always having a single value primary key makes performing UPSERTs very straightforward.

    Use additional indices to support multi-column keys which have meaning in your application.

提交回复
热议问题