Sub topic 2
Candidate Keys: What Can Identify a Row
Assume you know basic SELECT, INSERT, UPDATE, and DELETE, can create tables, and understand rows, columns, data types, and NULL.
A candidate key is a column, or a set of columns, that can uniquely identify each row in a table. It must meet two requirements:
- Uniqueness: no two rows have the same key value.
- Minimality: removing any column from the key would make it possible for duplicates to exist.
A table can have several candidate keys. You choose one of them as the primary key, the table's main identifier. The other candidate keys usually receive UNIQUE constraints.
Finding candidate keys
Imagine a customers table:
| customer_id | name | |
|---|---|---|
| 101 | [email protected] | Ana |
| 102 | [email protected] | Ben |
If customer_id is generated and never reused, it can identify a customer. If each email address is also required to be different, email can identify the same customer. Both are candidate keys.
The pair (name, email) is not a good candidate key if email alone is already unique. The pair is not minimal because one of its columns is unnecessary.
CREATE TABLE customers (
customer_id INTEGER GENERATED ALWAYS AS IDENTITY,
email VARCHAR(255) NOT NULL,
name VARCHAR(100) NOT NULL,
CONSTRAINT pk_customers PRIMARY KEY (customer_id),
CONSTRAINT uq_customers_email UNIQUE (email)
);This table declares customer_id as the primary key and preserves email as another candidate key. A primary key is automatically both NOT NULL and unique. A UNIQUE constraint prevents duplicate non-NULL values, but NULL handling differs among database systems. Use NOT NULL when every row must have a value.
Choosing among candidates
Prefer a candidate key that is:
- stable over the row's lifetime;
- always available when the row is created;
- short enough for indexes and foreign keys;
- independent of changeable business meaning.
An email address may identify a customer today, but users can change it. A generated numeric identifier has less business meaning and usually remains stable. This is why many designs use a generated surrogate primary key plus UNIQUE constraints for important natural identifiers.
Candidate keys also guide foreign-key design. Other tables should reference a primary key or another column set that has a uniqueness guarantee. Without that guarantee, a reference could match multiple parent rows.
Exercise
A table has account_id as a generated identity and username marked NOT NULL UNIQUE. What candidate keys does it have, and which key would you choose as the primary key?
Show answer
It has account_id and username as candidate keys. Choose the stable generated account_id as the primary key, while retaining username as a UNIQUE constraint if the business rule requires unique usernames.