Surrogate key vs Natural key

best practicesdatabase-designnatural-keysurrogate-key

I have a table called devices. Most of the devices that will get stored in this table can be uniquely identified by their serial number and part number. But there are some device types that do not have serial number and part number assigned to them. Instead they can be uniquely identified by another field (internal id).

Should I create a surrogate key for this table or should I create a composite primary key (serial number, part number, internal id) and insert default values to the serial number and part number columns when they are not supplied? The device types that do not have part number and serial number now, will have the numbers assigned to them in the future releases (may be 5 years from now). Should I create a surrogate key or a composite key in this scenario? Or using the three unique attributes, should I create a hash in the program and use that as a surrogate key for the tables?

Best Answer

Use the surrogate key as the primary key for the moment. When natural keys become available, make them non-nullable unique constraints.

By the YAGNI principle, you should only code for "real-life" current requirements - a primary key that may (or may not) arrive in 5 years is not worth considering now!

Surrogate keys are very widely used in practice, much to the horror of purists: the rest of us just use them! See this Stack Overflow answer (as well as the rest of the thread).