I have a table with 3 fields: color, fruit, date. I can pick 1 fruit and 1 color, but I can do this only once each day.
examples:
- red, apple, monday
- red, mango, monday
- blue, apple, monday
- blue, mango, monday
- red, apple, tuesday
The two ways in which I could build the table are:
1.- To have color, fruit and date be a composite primary key (PK). This makes it easy to insert data into the table because all the validation needed is done by the database.
- PK color
- PK fruit
- PK date
2.- Have and id column set as PK and then all the other fields. Many say thats the way it should be, because composite PKs are evil. For example, CakePHP does no support them.
- PK id
- color
- fruit
- date
Both have advantages. Which would be the ‘better’ approach?
I actually prefer the second option, with the ID column as the “surrogate” primary key. Most database gurus would probably say that you should look for the “natural key” in the table (which could be composite), but I think it’s easier to work with single-column surrogate PKs, especially when using ORMs. Even if the ORM supports composite keys, it’s still easier to work with a surrogate key. It’s also easier to write queries against tables that use IDs, as opposed to composite keys.
You can use a unique constraint to achieve the in-database validation of the uniqueness these three columns.