Should all database tables have a primary key?

前端 未结 7 1493
旧巷少年郎
旧巷少年郎 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:34

    Yes, it is good practise to have a primary key on every table.

    But, NOT every table should have a single auto number id column. I felt the need to spell that out, because for some reason lots of people tend to throw in an extra ID in all tables even though a perfectly good candidate already exist. For example, a many-to-many table representing Users <-> Groups should use {user_id, group_id}.

    Apart from stopping duplicates at the door, a primary key constraint also carries information which is used by the optimizer when generating execution plans.

    This is why I always, or at least with very few exceptions, have a primary key on all tables I create. In fact, I even create primary keys on reporting tables where most of the columns are part of the primary key. Because during development, I will get at least one unique constraint violation because I did something wrong. With shitloads of data and no constraint in place I wouldn't have spotted the error.

提交回复
热议问题