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

后端 未结 4 815
無奈伤痛
無奈伤痛 2021-02-04 10:06

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

相关标签:
4条回答
  • 2021-02-04 10:46

    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 讨论(0)
  • 2021-02-04 10:47

    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.

    0 讨论(0)
  • 2021-02-04 10:50

    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

    0 讨论(0)
  • 2021-02-04 10:55

    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.

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