What is the difference b/w Primary Key and Unique Key

前端 未结 11 1766
孤城傲影
孤城傲影 2020-12-24 13:07

I tried to find it out in google but not satisfactory answer is given out there. Can anybody explain the solid difference.

actually if Primary key is used to sele

11条回答
  •  生来不讨喜
    2020-12-24 13:13

    Primary Key and Unique Key are used for different things - understanding what they are for will help you decide when to use them.

    The primary key is used to identify a row of data in a table. It is used whenever you need to refer to a particular row, eg. in other tables or by application code etc. In order to identify a row, the values of a PK must be unique. Furthermore, they can't be null, because most DBMS treat null as not equal to null (since null typically means "unknown"). A table can only have one PK. All tables in your database should have a PK (although this is not enforced by most DBMS), and PK can span multiple columns.

    Unique key constraints are used to ensure that data is not duplicated in two rows in the database. One row in the database is allowed to have null for the value of the unique key constraint. Although a table should have a PK, it need not have any additional unique keys. However, tables can have more than one unique key if that meets your needs. Like PKs, unique keys can span multiple columns.

    It is also worth knowing that, by default, many DBMS index and physically order tables on disk using the PK. This means that looking up values by their PK is faster than using other values in a row. Typically, however, you can override this behaviour if required.

提交回复
热议问题