Question

I have a Country table which includes the columns ID, Name and Code. All three of these columns should contain unique values and cannot be NULL.

My question is, would I be better to create a primary key on the ID column and a unique constraint for the Name and Code columns (in one index, I guess), or would it be better to just include the Name and Code columns in the primary key with the ID? And why? Are there potential downsides or complexities that will result from having a multiple-column primary key?

Was it helpful?

Solution

First of all - yes, a compound primary key made up of three columns makes it more annoying to join to this table - any other table wanting to join to the Country table will also have to have all three columns to establish the join.

And more importantly - it's NOT the same restriction!

If you have the PK on ID and a unique constraint on both Code and Name separately, then this is NOT valid:

ID    Code     Name
--------------------------
41    CH       Switzerland
341   CH       Liechtenstein
555   LIE      Liechtenstein

because the Code of CH and the Name of Liechtenstein both appear twice.

But if you have a single PK on all three columns together - then this is valid because each row has a different tuple of data - (41, CH, Switzerland) is not the same as (341, CH, Liechtenstein) and therefore, those two rows are admissible.

If you put the PK on all three columns at once, then the uniqueness only extends to the whole tuple (all three columns) - each column separately can have "duplicates".

So it really boils down to

  • what you really need (which uniqueness)
  • how easy you want to make it to join to this table
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top