Should all database tables have a primary key?

前端 未结 7 1559
旧巷少年郎
旧巷少年郎 2021-01-04 22:35

Is it good practice to give every database table a primary key? It seems to me that if the primary key is not explicitly needed, then it would just be extra clutter in my d

7条回答
  •  佛祖请我去吃肉
    2021-01-04 23:19

    While primary keys are hugely useful (and I use them all the time), let's be clear that there's no need to create a primary key if you don't need one. There are cases where you don't need one, among them:

    • a table that just collects data (for persistence purposes) to be queried itself and not related to other tables where the other tables needed to find the precise row being related to
    • you don't need to enforce any kind of uniqueness in your table

    In both cases above, you may be interested purely in aggregate info about a table and not in identifying a row uniquely. I believe there are others. But not using primary keys are fine -- this is why they are not required when you create a table (in most systems).

提交回复
热议问题