Concept:
In a relational database,
keys are attributes or sets of attributes that help uniquely identify records in a table and establish relationships between tables. Keys play an important role in maintaining data integrity and ensuring efficient data retrieval.
1. Primary Key:
A
Primary Key is a field or a combination of fields that uniquely identifies each record in a table. It ensures that no two rows have the same value for the primary key.
Characteristics of Primary Key:
- Each value must be unique.
- It cannot contain NULL values.
- There can be only one primary key in a table.
Example:
In a \texttt{Student} table, the \texttt{Student_ID} can act as the primary key because it uniquely identifies each student.
2. Foreign Key:
A
Foreign Key is a field in one table that refers to the
primary key of another table. It is used to establish a relationship between two tables.
Characteristics of Foreign Key:
- It maintains referential integrity between tables.
- It can contain duplicate values.
- It may contain NULL values if the relationship is optional.
Example:
In an \texttt{Orders} table, the \texttt{Student_ID} field may refer to the \texttt{Student_ID} in the \texttt{Student} table.
3. Candidate Key:
A
Candidate Key is an attribute or a set of attributes that can uniquely identify a record in a table. A table may have multiple candidate keys.
From the set of candidate keys, one key is selected as the
primary key.
Characteristics of Candidate Key:
- Must uniquely identify each record.
- Cannot contain duplicate values.
- A table may have multiple candidate keys.
Example:
In a \texttt{Student} table, both \texttt{Student_ID} and \texttt{Email} could uniquely identify a student.
Thus, both are candidate keys, but one of them is chosen as the primary key.