Is it OK not to use a Primary Key When I don't Need one

前端 未结 12 1314
南笙
南笙 2020-12-17 23:06

If I don\'t need a primary key should I not add one to the database?

相关标签:
12条回答
  • 2020-12-17 23:13

    You do need a primary key. You just don't know that yet.

    0 讨论(0)
  • 2020-12-17 23:23

    A primary key is mainly formally defined to aid referencial Integrity, however if the table is very small, or is unlikely to contain unique data then it's an un-necessary overhead. Defining indexes on the table can normally be used to imply a primary key without formally declaring one. However you should consider that defining the Primary key can be useful for Developers and Schema generation or SQL Dev tools, as having the meta data helps understanding, and some tools rely on this to correctly define the Primary/foreign key relationships in the model.

    0 讨论(0)
  • 2020-12-17 23:24

    You should always have a primary key, even if it's just on ID. Maybe NoSQL is what you're after instead (just asking)?

    0 讨论(0)
  • 2020-12-17 23:26

    I don't know. I have used a couple tables where there is just a single row and a single column. Will always only be a single row and a single column. There is no foreign key relationships.

    Why would I put a primary key on that?

    0 讨论(0)
  • 2020-12-17 23:26

    That depends very much on how sure you can be that you don't need one. If you have just the slightest bit of doubt, add one - you'll thank yourself later. An indicator being if the data you store could be related to other data in your DB at one point.

    One use case I can think of is a logging kind-of table, in which you simply dump one entry after the other (to properly process them later). You probably won't need a primary key there, if you're storing enough data to filter out the relevant messages (like a date). Of course, it's questionable to use a RDBMS for this.

    0 讨论(0)
  • 2020-12-17 23:27

    A primary key uniquely identifies a row in your table.

    The fact it's indexed and/or clustered is a physical implementation issue and unrelated to the logical design.

    You need one for the table to make sense.

    0 讨论(0)
提交回复
热议问题