Search code examples
mysqlinnodb

Composite keys v surrogate keys for weak entities in MySQL


Until now, I have been creating surrogate keys, to act as primary keys for each of my tables. I'm happy with this for the most part.

However, for weak entities that are dependent upon other tables, I have read that it is preferable to use a foreign key and one of the weak entity's attributes to create a composite key that acts as the primary key.

Is there any benefit to this method or can I continue using surrogate keys for all of my tables?


Solution

  • Two-thirds of the tables I have ever written have a "natural" PRIMARY KEY. Sometimes it is "composite". There are even times where I put a surrogate after another column in the PK.

    The reasons I use for deciding vary with the application and the size of the table:

    • Often there is a 'natural' PK.
    • Often id AUTO_INCREMENT is simply a waste of space, speed, etc.
    • Sometimes there are queries that would benefit from fetching a "range" of rows -- Having the PK provide those rows consecutively can be a performance boost, hence tailoring the PK for that.
    • If there are lots of secondary keys, it is usually better to have a shorter PK. (Each secondary key has a copy of the PK column(s).) This is sometimes a valid argument for adding a surrogate.
    • Similarly, if several other tables need to link to this table, it is better to have a short PK. (A surrogate is often shorter than a 'natural'.)
    • TEXT and BLOB columns cannot be in a PK.

    Here are 3 examples where a a composite natural PK is clearly better than a surrogate:

    Note: "weak entity" and "foreign key" are not considerations in my decision making.