3.2 Keys in Relational Model: Candidate, Primary & Foreign Keys
💡 Core Intuition
🍳 The Everyday Analogy: Identifying Citizens
Imagine a government registry office managing 100 million citizens. To find or update any specific individual's file without error, you need a mechanism that uniquely distinguishes one human from everyone else.
- Overkill identification (Super Key): Looking someone up using their
(Passport Number, Favorite Color, Shoe Size)is 100% unique, but contains redundant baggage. - Minimal unique identifier (Candidate Key): Looking someone up using solely their
Passport Numberor solely theirNational ID (SSN)is completely sufficient and contains zero fluff. - The Official Standard (Primary Key): The registry picks one specific identifier (
National ID) as the universal system reference across all public departments. - Secondary Identifiers (Alternate Keys): The unused minimal identifiers (
Passport Number) remain valid alternates. - Cross-Department Linkage (Foreign Key): When the Department of Motor Vehicles records a driver's license, it stamps the driver's
National IDinto the license record to link back to the central citizen registry.
💻 Bridging to Computer Science
In the relational model, a Key is a single attribute or a minimal collection of attributes whose values are guaranteed to uniquely identify each tuple in a relation instance. Keys prevent tuple ambiguity, enforce entity integrity, and establish relational links between separate tables.
📚 Core Deep-Dive & Concepts
1. The Key Classification Spectrum
In database management systems, keys are categorized based on their uniqueness, minimality, and architectural purpose:
| Key Type | Formal Definition | Uniqueness | Minimality Required? | Allows NULL? |
|---|---|---|---|---|
| Super Key () | Any superset of attributes that uniquely identifies a tuple. | Yes | No | Context-dependent |
| Candidate Key () | A minimal Super Key (no proper subset is a Super Key). | Yes | Yes | At least one CK must be NOT NULL |
| Primary Key () | The single Candidate Key chosen by the database designer. | Yes | Yes | Never (NOT NULL) |
| Alternate Key () | Candidate keys not chosen as the Primary Key (). | Yes | Yes | Often permitted in standard SQL |
| Foreign Key () | Attribute referencing the Primary Key of another or same table. | No (can repeat) | Determined by target | Yes (unless declared NOT NULL) |
| Composite Key | A key formed by combining two or more distinct attributes. | Yes | Yes (if minimal) | Restricted on PK members |
| Surrogate Key | An artificial, system-generated identifier (e.g. AUTO_INCREMENT ID, UUID). | Yes | Yes | Never |
2. Super Key () & Mathematical Counting
Definition: A Super Key is a set of one or more attributes that, taken collectively, allows us to identify uniquely a tuple in the relation.
The Fundamental Axiom: Every superset of a Super Key is also a Super Key.
The largest possible Super Key in any relation is the set containing all attributes:
Mathematical Derivation: Maximum Number of Superkeys
Consider a relation containing distinct attributes:
Case A: Exactly One Single-Attribute Candidate Key
Let attribute be the lone candidate key. Any superkey must contain , combined with any arbitrary subset of the remaining attributes:
Case B: Every Attribute is Individually a Candidate Key
If every attribute () is an individual candidate key, then any non-empty subset of the attributes forms a valid superkey:
(We subtract because the empty set cannot identify a tuple).
Case C: Two Disjoint Candidate Keys (Inclusion-Exclusion Principle)
Let have two candidate keys: and .
By the Principle of Inclusion-Exclusion:
- Superkeys containing :
- Superkeys containing :
- Superkeys containing both and (i.e. ):
3. Candidate Key () & Prime Attributes
Formal Definition: A Candidate Key of a relation schema is a minimal superkey:
- Uniqueness Property: In every legal relation state , no two distinct tuples have the same value for .
- Minimality (Irreducibility) Property: If , then is not a superkey. That is, no proper subset of is a superkey.
Example: Superkey vs Candidate Key
Let relation satisfy functional dependencies where:
Both and are valid Super Keys because each can uniquely determine all attributes of the relation.
However, because , the attribute set fails the minimality test.
Therefore:
- is a Super Key, but not a Candidate Key.
- is both a Super Key and a Candidate Key.
Prime vs. Non-Prime Attributes
Prime Attribute: An attribute that is a member of at least one candidate key of the relation schema .
Non-Prime Attribute: An attribute that is not a member of any candidate key of .
Analytical Rule: If a relation has candidate keys and , the prime attributes are . Even though is absent from , its presence in makes it prime.
4. Primary Key () & Alternate Keys ()
Primary Key: A database designer or DBA selects exactly one candidate key from the available candidate keys to serve as the principal tuple identifier.
- Rule 1: A relation schema can have at most one Primary Key.
- Rule 2: No attribute belonging to the Primary Key can ever accept
NULLvalues. - Rule 3: Primary key values should ideally be immutable (rarely or never updated in production).
Alternate Key: Any candidate key that was not chosen as the Primary Key:
Subset Hierarchy of Keys
The relationship between keys forms a strict nested containment:
5. Foreign Key () & Referential Integrity
Definition: A Foreign Key is a set of attributes in a referencing relation that corresponds to and references the Primary Key (or unique key) of a referenced relation .
The Fundamental Constraint of Referential Integrity:
Every value appearing in the foreign key column must either:
- Exist as a valid primary key value in the referenced relation, OR
- Be explicitly
NULL(indicating an unassigned or optional relationship).
Self-Referencing (Recursive) Foreign Keys
A table can reference its own primary key. This is called a Recursive Foreign Key or Self-Referential Constraint.
Canonical Schema:
Where is a foreign key referencing within the exact same Employee table. The CEO or topmost executive will store NULL in .
📐 Architecture / Visual Blueprint
🏭 In The Real World: Production Case Study
Natural Primary Keys vs Synthetic Surrogate Keys in Stripe API Architecture
When Stripe engineers designed the billing and customer database schemas, they evaluated two key models:
- Natural Composite Primary Key: Combining
(country_code, tax_id_number, registered_business_name).- Drawback: Tax identification formats change across sovereign jurisdictions; businesses re-incorporate or change legal names. Updating natural primary keys cascades expensive locks across millions of payment ledger rows.
- Surrogate Primary Key: Auto-generating globally unique, prefixed cryptographic IDs (e.g.
cus_9sA2bKL01m,ch_3Mwj9v2eZvKYlo2C0O).- Production Benefit: The primary key is guaranteed to be immutable, fixed-width (indexed rapidly via B+ Trees), and completely shielded from external business domain mutation. Alternate natural candidate keys (like tax ID) are protected via secondary unique constraints with
NULLsupport.
- Production Benefit: The primary key is guaranteed to be immutable, fixed-width (indexed rapidly via B+ Trees), and completely shielded from external business domain mutation. Alternate natural candidate keys (like tax ID) are protected via secondary unique constraints with
🎯 Exam & Interview Pitfall Check
Question 1: Prove mathematically why a relation with attributes has at most superkeys.
Answer:
A relation schema with distinct attributes possesses total subsets (the power set). A superkey is any non-empty subset that uniquely identifies a row. In the theoretical extreme where every single attribute is individually unique (each is a candidate key), any non-empty combination of attributes will also uniquely identify a row. Excluding the empty set (which contains zero attributes and cannot identify a tuple), the total possible superkeys equals .
Question 2: What is the difference between a Composite Key and a Compound Key?
Answer:
- Composite Key: Any key that consists of two or more attributes. The individual constituent attributes may or may not be foreign keys on their own.
- Compound Key: A specific subtype of composite key where at least one of the constituent attributes is an explicit foreign key referencing another table (e.g. a junction table for an M:N relationship where both columns form the PK and each is simultaneously an FK).
Trap 1: "Can a Foreign Key have duplicate values or NULL values?"
Answer: Yes to both. A foreign key represents the "Many" side of a 1:N relationship, meaning multiple child tuples can legally reference the exact same parent primary key (e.g. multiple students sharing Dept_Code = 101). Furthermore, unless explicitly restricted with a NOT NULL constraint, foreign key attributes may hold NULL values to denote unassigned relationships.
Trap 2: "Is every minimal set of attributes a candidate key?"
Answer: No. Minimality is only one of two required conditions. The set must first be a Super Key (uniquely identify all tuples). Only among valid superkeys does the minimality condition determine candidate key status.
Never Study in Isolation. Join Binary Dose.
Connect with fellow engineers, clear conceptual doubts, and get 2 visual breakdowns & engineering mental models daily across our community channels.
Discord Community
Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.