What is the difference between a candidate key and a primary key?

后端 未结 11 1212
不思量自难忘°
不思量自难忘° 2020-12-23 17:24

Is it that a primary key is the selected candidate key chosen for a given table?

11条回答
  •  悲哀的现实
    2020-12-23 17:56

    A primary key is a column (or columns) in a table that uniquely identifies the rows in that table.

    CUSTOMERS
    
    
    CustomerNo  FirstName   LastName
    1   Sally   Thompson
    2   Sally   Henderson
    3   Harry   Henderson
    4   Sandra  Wellington
    

    For example, in the table above, CustomerNo is the primary key.

    The values placed in primary key columns must be unique for each row: no duplicates can be tolerated. In addition, nulls are not allowed in primary key columns.

    So, having told you that it is possible to use one or more columns as a primary key, how do you decide which columns (and how many) to choose?

    Well there are times when it is advisable or essential to use multiple columns. However, if you cannot see an immediate reason to use multiple columns, then use one. This isn't an absolute rule, it is simply advice. However, primary keys made up of single columns are generally easier to maintain and faster in operation. This means that if you query the database, you will usually get the answer back faster if the tables have single column primary keys.

    Next question — which column should you pick? The easiest way to choose a column as a primary key (and a method that is reasonably commonly employed) is to get the database itself to automatically allocate a unique number to each row.

    In a table of employees, clearly any column like FirstName is a poor choice since you cannot control employee's first names. Often there is only one choice for the primary key, as in the case above. However, if there is more than one, these can be described as 'candidate keys' — the name reflects that they are candidates for the responsible job of primary key.

提交回复
热议问题