Primary keys

When we design entities, we choose an attribute or a combination of multiple attributes that can be used to uniquely identify an entity as the primary key of that type of entity.

By nature, primary keys are unique. For example, since two users cannot have the same email address, we could use it as the primary key of the User entities. However, that won't work in applications that allow users to change their email addresses. The attribute or a combination of the attributes that are used as the primary key must be stable. That is, the value of a primary key must not be changed throughout the life cycle of that entity, for the same reason that it is not a good idea to use an attribute username as the primary key for the User entities. Even though the email address and the username attribute cannot be used as a primary key, they can still be used to identify users, for instance, you can still use a user's email address or username to find that user. We call these types of attributes candidate keys.

In practice, it is common to use a system-generated unique value as the primary key of a type of entity. For example, we can let MySQL generate integer values for the id column of a table and use that column as the primary key. With MongoDB, the database will autogenerate a unique value for each document's _id attribute, which can be used as the primary key. Or, we can generate a Universally Unique Identifier (UUID), such as e7f71282-37c6-41fe-a413-8fc0d4d32eed, in the application and use it as the value of a primary key. All of these system-generated primary keys are called surrogate keys.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.255.178