When we don't need a primary key for our table?

怎甘沉沦 提交于 2019-12-03 10:12:14

问题


Will it ever happen that we design a table that doesn't need a primary key?


回答1:


No.

The primary key does a lot of stuff behind-the-scenes, even if your application never uses it.

For example: clustering improves efficiency (because heap tables are a mess).

Not to mention, if ANYONE ever has to do something on your table that requires pulling a specific row and you don't have a primary key, you are the bad guy.




回答2:


Yes.

If you have a table that will always be fetched completely, and is being referred-to by zero other tables, such as some kind of standalone settings or configuration table, then there is no point having a primary key, and the argument could be made by some that adding a PK in this situation would be a deception of the normal use of such a table.

It is rare, and probably when it is most often done it is done wrongly, but they do exist, and such instances can be valid.




回答3:


Depends.

What is primary key / unique key?

In relational database design, a unique key can uniquely identify each row in a table, and is closely related to the Superkey concept. A unique key comprises a single column or a set of columns. No two distinct rows in a table can have the same value (or combination of values) in those columns if NULL values are not used. Depending on its design, a table may have arbitrarily many unique keys but at most one primary key.

So, when you don't have to differentiate (uniquely identify) each row,
you don't have to use primary key

For example, a big table for logs,
without using primary key, you can have fairly smaller size of data and faster for insertion




回答4:


Primary key not mandatory but it is not a good practice to create tables without primary key. DBMS creates auto-index on PK, but you can make a column unique and index it, e.g. user_name column in users table are usually made unique and indexed, so you may choose to skip PK here. But it is still a bad idea because PK can be used as foreign key for referential integrity.

In general, you should almost always have PK in a table unless you have very strong reason to justify not having a PK.

Link tables (in many to many relationship) may not have a primary key. But, I personally like to have PK in those tables as well.



来源:https://stackoverflow.com/questions/5496008/when-we-dont-need-a-primary-key-for-our-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!