Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relational database design question - Surrogate-key or Natural-key?

Which one is the best practice and Why?

a) Type Table, Surrogate/Artificial Key

Foreign key is from user.type to type.id: alt text

b) Type Table, Natural Key

Foreign key is from user.type to type.typeName: alt text

like image 524
aryaxt Avatar asked Sep 19 '10 22:09

aryaxt


People also ask

Should I use surrogate key or natural key?

1: A primary key value must be unique A primary key uniquely identifies each record within a table and relates records to additional data stored in other tables. A natural key might require several fields to accomplish a unique identity for each record. A surrogate key is unique in and of itself.

What is surrogate key and natural key with example?

has a relationship with the rest of the column values in a given data record. Here are some examples of natural keys values: Social Security Number, ISBN, and. TaxId. A surrogate key like a natural key is a column that uniquely. identifies a single record in a table.

What is a surrogate key in relational database?

A surrogate key is a unique key for an entity in the client's business or for an object in the database. Sometimes natural keys cannot be used to create a unique primary key of the table. This is when the data modeler or architect decides to use surrogate or helping keys for a table in the LDM.


2 Answers

I believe that in practice, using a natural key is rarely the best option. I would probably go for the surrogate key approach as in your first example.

The following are the main disadvantages of the natural key approach:

  • You might have an incorrect type name, or you may simply want to rename the type. To edit it, you would have to update all the tables that would be using it as a foreign key.

  • An index on an int field will be much more compact than one on a varchar field.

  • In some cases, it might be difficult to have a unique natural key, and this is necessary since it will be used as a primary key. This might not apply in your case.

like image 130
Daniel Vassallo Avatar answered Oct 04 '22 15:10

Daniel Vassallo


The first one is more future proof, because it allows you to change the string representing the type without updating the whole user table. In other words you use a surrogate key, an additional immutable identifier introduced for the sake of flexibility.

like image 43
Adam Byrtek Avatar answered Oct 04 '22 16:10

Adam Byrtek