Search code examples
sqldatabaseprimary-keycomposite-primary-keyrdbms

How to pick a primary key in a relational database when several columns are unique?


If a table has two columns that act as a composite candidate key (uniquely identifying each row), is it a good practice to create a surrogate key and use it as the primary key instead?

The reason would be: foreign keys referencing it would be simpler to read (referencing one column instead of two).

Also, if a surrogate key is used, should I create a unique constraint on the two columns previously mentioned?


Solution

  • You have actually asked several questions:

    1. If there are multiple columns (or sets of columns) that are unique from the logical standpoint, should I make a key on all of them?
    2. When there are multiple keys, how do I decide which to make primary?
    3. If there is already a natural key (or keys), can I replace it (them) with a surrogate key?
    4. If there is already a natural key (or keys), should I add a surrogate key?

    And here are the answers:

    1. Yes.
    2. From the logical standpoint, all keys are equivalent. However, there may be physical considerations in favor of making one of them primary over the others.
    3. No.
    4. It depends. More on that here.