Primary Key versus Unique Constraint?

前端 未结 16 1874
轮回少年
轮回少年 2020-12-13 03:49

I\'m currently designing a brand new database. In school, we always learned to put a primary key in each table.

I read a lot of articles/discussions/newsgroups posts

16条回答
  •  囚心锁ツ
    2020-12-13 04:14

    We need to make a distinction here between logical constructs and physical constructs, and similarly between theory and practice.

    To begin with: from a theoretical perspective, if you don't have a primary key, you don't have a table. It's just that simple. So, your question isn't whether your table should have a primary key (of course it should) but how you label it within your RDBMS.

    At the physical level, most RDBMSs implement the Primary Key constraint as a Unique Index. If your chosen RDBMS is one of these, there's probably not much practical difference, between designating a column as a Primary Key and simply putting a unique constraint on the column. However: one of these options captures your intent, and the other doesn't. So, the decision is a no-brainer.

    Furthermore, some RDBMSs make additional features available if Primary Keys are properly labelled, such as diagramming, and semi-automated foreign-key-constraint support.

    Anyone who tells you to use Unique Constraints instead of Primary Keys as a general rule should provide a pretty damned good reason.

提交回复
热议问题