Natural Key in SQL
A natural key, also known as a business key or domain key, is a unique identifier for a row in a database table that is derived from the real-world characteristics of the entity the row represents. In other words, a natural key is a column or set of columns that uniquely identifies a row in a table and is meaningful in the context of the business or domain being modeled.
For example, consider a table of employees in a company. A natural key for this table might be the employee's social security number, as this is a unique identifier for each employee and is meaningful in the context of the business.
In contrast, a surrogate key is a unique identifier that is assigned to a row in a table and has no inherent meaning in the context of the business or domain being modeled. Surrogate keys are often used as primary keys in database tables because they are simple to generate and can be easily changed if necessary.
Here's an example of how to create a table with a natural key in SQL:
CREATE TABLE employees ( employee_id INT NOT NULL, social_security_number VARCHAR(11) NOT NULL, first_name VARCHAR(255) NOT NULL, last_name VARCHAR(255) NOT NULL, PRIMARY KEY (employee_id), UNIQUE KEY (social_security_number) );
In this example, the
social_security_number column is the natural key for the
employees table, and the
employee_id column is the surrogate key. The
employee_id column is defined as the primary key of the table, but the
social_security_number column is defined as a unique key to ensure that each employee has a unique social security number.
Points to consider when working with natural keys
Here are a few more things to consider when working with natural keys in SQL:
Natural keys are often based on real-world characteristics of the entity being modeled, such as a person's social security number or a product's serial number.
Natural keys can be used as primary keys in a table, but it is more common to use a surrogate key as the primary key and use the natural key as a unique constraint or index. This can make it easier to change the natural key if necessary, as the primary key does not need to be changed.
Natural keys can be composite keys, consisting of multiple columns that together uniquely identify a row in a table.
It is important to carefully consider the design of a natural key, as changing the key in the future can be difficult and may require updating other tables that depend on the key.
Natural keys can be used to enforce relationships between tables, just like surrogate keys. However, natural keys may be more prone to change than surrogate keys, as they are often based on real-world characteristics that may change over time.