开发者

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

Will it ever happen that we design a table that doesn't need a pr开发者_StackOverflow中文版imary key?


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.


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜