Sub topic 2
Candidate keys: what can identify a row
This chapter assumes you can write CREATE TABLE statements, know the basic column constraints (NOT NULL, UNIQUE), and understand NULL as "unknown or missing". It covers the idea that comes before choosing a primary key: which sets of columns could identify a row.
Superkeys and candidate keys
A superkey is any set of columns whose combined values are unique across every row of a table. The whole row is always a superkey, because no two rows in a table are identical. Adding columns to a superkey gives you another superkey.
A candidate key is a superkey that is minimal. If you remove any column from it, it stops being unique. A table can have several candidate keys, and each one is a complete, independent way to find exactly one row.
Take a vehicles table:
CREATE TABLE vehicles (
vehicle_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
vin CHAR(17) NOT NULL UNIQUE,
plate_region CHAR(2) NOT NULL,
plate_number VARCHAR(10) NOT NULL,
model VARCHAR(50) NOT NULL,
UNIQUE (plate_region, plate_number)
);This table has three candidate keys:
vehicle_id, a generated number.vin, the vehicle identification number assigned by the manufacturer.(plate_region, plate_number), because a plate number is only unique within a region.
The set (vin, model) is a superkey, since vin alone already guarantees uniqueness. It is not a candidate key, because you can drop model and keep uniqueness. Likewise, plate_number alone is not a candidate key. Two regions can issue the same number.
Uniqueness is a rule, not an observation
A candidate key is a statement about what the data is allowed to contain, not about what it contains today. Suppose a people table currently has no two rows with the same last_name. That does not make last_name a candidate key. The next insert can legitimately repeat a name.
To decide whether a column set is a candidate key, ask whether the real-world domain guarantees uniqueness, now and in the future. Then make the database enforce that rule. A column you believe is unique but have not constrained can quietly acquire duplicates.
Common false candidates:
- Names. Different people share them.
- Email addresses, if your business lets people share a mailbox or lets users register twice.
- Phone numbers, which are reassigned and shared by households.
- Timestamps. Two rows can arrive in the same microsecond.
Candidate keys must not be NULL
A key identifies a row, so every column of a candidate key should be NOT NULL. The primary key constraint enforces this for you. For alternate keys you must write it yourself:
CREATE TABLE accounts (
account_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
email VARCHAR(255) NOT NULL UNIQUE
);Without NOT NULL, a UNIQUE column behaves differently across databases, because SQL treats two NULLs as "not known to be equal".
Alternate keys
You pick one candidate key as the primary key. The remaining candidate keys are called alternate keys. SQL has no ALTERNATE KEY clause, so you enforce them with UNIQUE plus NOT NULL, as vin and (plate_region, plate_number) are above.
Declaring alternate keys is worth the effort for three reasons:
- They stop duplicate real-world entities, such as the same vehicle entered twice under different generated ids.
- They document how people and applications look rows up.
- Foreign keys can reference them. A foreign key must point at a primary key or a
UNIQUEcolumn set, so an alternate key can serve as a link target.
Each UNIQUE constraint creates an index behind the scenes in most databases, so lookups by vin are fast and each constraint adds a small cost to writes.
Unique does not always mean equal
A constraint compares stored values exactly. For text, that raises two problems:
[email protected]and[email protected]are different strings in PostgreSQL, so both pass a plainUNIQUEcheck.- Stray spaces make
'abc'and'abc 'differ.
To make the rule match the business rule, enforce uniqueness on a normalized expression:
CREATE TABLE members (
member_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email VARCHAR(255) NOT NULL
);
CREATE UNIQUE INDEX uq_members_email_lower
ON members (lower(email));
INSERT INTO members (email) VALUES ('[email protected]');
-- Fails: lower('[email protected]') already exists
INSERT INTO members (email) VALUES ('[email protected]');A unique index on an expression is not a table constraint, so a foreign key cannot reference it. If other tables need to link to email, store a normalized value in the column, or link to the primary key instead.
Choosing among candidate keys
The primary key is one of the candidates, and you decide which. The next chapters cover the trade-offs between natural and surrogate keys in detail. For now, use these questions to rank candidates:
| Question | Prefer a candidate that... |
|---|---|
| Does the value ever change? | Never changes. Updating a key means updating every row that references it. |
| How many columns does it have? | Has fewer columns. Every referencing table repeats the key. |
| Is it always known at insert time? | Is always available and never NULL. |
| Do you control it? | You control, not an outside party that might reuse or reformat values. |
In the vehicles example, a VIN looks stable, but VINs can be mistyped and corrected, and older vehicles may not have a standard one. Plates change when a vehicle moves region. A generated vehicle_id is stable and small, so it makes a good primary key, with the other two kept as alternate keys.
Common errors
- Declaring a key from sample data. The rule must come from the domain, not from the rows you happen to see.
- Making a superkey the primary key. A key such as
(vin, model)works but is not minimal. It hides the real rule, and it lets two rows share avinif they differ inmodel. - Forgetting alternate keys. With only a surrogate primary key, nothing stops the same real-world entity from appearing twice.
- Leaving key columns nullable. Rows with NULL in a key cannot be reliably identified.
- Ignoring case and whitespace. Plain
UNIQUEon text does exact comparison.
Exercise
A table enrollments(student_id, course_id, term, grade) records one grade per student per course per term. A student may take the same course in different terms. Which column sets are candidate keys, and is (studentid, courseid, term, grade) one?
Show answer
The only candidate key is (studentid, courseid, term). Together they identify exactly one enrollment, and removing any one column allows duplicates, such as a retake in another term. (studentid, courseid, term, grade) is a superkey but not a candidate key, because grade can be removed without losing uniqueness.
Exercise
Why does a plain UNIQUE constraint on email not stop '[email protected]' and '[email protected]' from both being stored in PostgreSQL, and how do you fix it?
Show answer
UNIQUE compares values exactly, and the two strings differ in case. Create a unique index on the normalized expression, for example CREATE UNIQUE INDEX uqmembersemail_lower ON members (lower(email)).