
280 views
MySQL Primary Key vs Candidate Key
The context of relational databases, a “candidate key” is a broader concept compared to a “primary key.” Both are used to uniquely identify records in a table and enforce data integrity, but there are important differences between them.
Candidate Key:
- Definition:
- A candidate key is a column or a set of columns that could be used as the primary key of a table.
- It satisfies the uniqueness and non-null requirements, just like a primary key.
- Uniqueness:
- Like a primary key, a candidate key enforces the uniqueness constraint.
- There can be multiple candidate keys in a table.
- Nullability:
- Candidate key columns cannot contain NULL values, just like primary keys.
- Role:
- A candidate key serves as a potential primary key option for a table.
- Not all candidate keys become primary keys, as only one is chosen as the primary key.
- Indexing:
- Like a primary key, a candidate key can automatically create an index on the table to enforce uniqueness and improve performance.
Primary Key:
- Definition:
- A primary key is a specific candidate key that is chosen to uniquely identify records in a table.
- It is selected as the main identifier for the table.
- Uniqueness:
- A primary key enforces the uniqueness constraint just like a candidate key.
- Nullability:
- Primary key columns cannot contain NULL values, just like candidate keys.
- Role:
- The primary key serves as the main identifier for the table.
- It is used as a reference in foreign key relationships to establish relationships between tables.
- Indexing:
- A primary key automatically creates an index on the table, often optimizing retrieval and search operations.
Usage:
- Use candidate keys to identify all the possible options for primary keys in a table.
- Choose one of the candidate keys as the primary key to be the main identifier for the table.
Example:
Consider a Students
table with columns student_id
, student_email
, and student_roll
. Both student_id
and student_email
could be potential candidate keys, as they are unique and non-null. However, you might choose student_id
as the primary key for this table.
-- Candidate Keys
ALTER TABLE Students
ADD CONSTRAINT unique_email UNIQUE (student_email),
ADD CONSTRAINT unique_roll UNIQUE (student_roll);
-- Primary Key
ALTER TABLE Students
ADD PRIMARY KEY (student_id);
In summary, a candidate key represents all the possible options for a primary key in a table, while a primary key is the specific candidate key chosen to uniquely identify records and serve as the main identifier.