Historical Context & Motivation
Before relational databases existed, data was stored in flat files and hierarchical or network models that made cross-referencing records brittle and error-prone. A programmer who wanted to link a customer to their orders had to hard-code pointer chains or navigate complex record-level associations, and any structural change could cascade through the entire codebase. The concept of keys emerged as a principled solution to this problem: a declarative mechanism for uniquely identifying rows and establishing reliable links between tables. The journey from ad-hoc file systems to the rigorous relational algebra we use today was driven by a handful of seminal contributions that shaped how we think about data integrity.
The core question that motivated all of this work remains central today: how do you guarantee that every record in a database is uniquely addressable, and that relationships between records remain consistent as data changes? Primary keys and foreign keys are the answer that the relational model provides, and understanding them conceptually is a prerequisite for designing sound schemas.
Core Principles & Definitions
At its heart, the relational model treats a database as a collection of relations (tables), where each relation has a heading (a set of attribute names and types) and a body (a set of tuples). To manipulate data reliably, we need two guarantees: every tuple must be distinguishable from every other tuple in the same relation, and a tuple in one relation that references a tuple in another relation must point to something that actually exists. These guarantees are enforced by primary keys and foreign keys, respectively.
Candidate Key
Primary Key (PK)
Foreign Key (FK)
Referential Integrity
Surrogate vs. Natural Key
Visual Explanation β Table Relationships
The following diagram illustrates two relations β students and enrollments β and the key constraints that bind them. The primary key column in each table is marked with a key icon, while the foreign key in the child table is connected by an arrow to the primary key it references in the parent table.
enrollments.student_id to students.student_id represents the foreign key constraint. Every value in the FK column must match an existing PK value in the parent table, or be NULL if the column permits it.Notice that enrollments has its own primary key (enrollment_id), which uniquely identifies each enrollment record. The student_id column in enrollments is a foreign key β it does not need to be unique within enrollments (a student can enroll in many courses), but every value it stores must correspond to some student_id already present in students. This one-to-many cardinality β one student, many enrollments β is the most common relationship pattern in relational design.
How Keys Work β Formal Properties
While keys are a conceptual construct, their properties can be stated formally. Understanding these properties helps you distinguish between candidate keys, super keys, and the chosen primary key, and it clarifies exactly what a foreign key constraint guarantees at the logical level.
Uniqueness & Minimality of Candidate Keys
Entity Integrity Rule
Codd's entity integrity rule states that no component of a primary key may be null. The rationale is straightforward: if a primary key's purpose is to uniquely identify a tuple, then allowing nulls would make identification impossible, because NULL β NULL in SQL's three-valued logic. This rule applies strictly to primary keys; other candidate keys (alternate keys) may permit nulls in some SQL implementations, though doing so is generally discouraged.
Cascading Referential Actions
When a row in the parent table is deleted or its primary key is updated, the RDBMS must decide what to do with dependent rows in child tables. SQL defines several referential actions: CASCADE propagates the change to all dependent rows; SET NULL sets the FK column to null; SET DEFAULT reverts it to a default value; RESTRICT (and its close cousin NO ACTION) rejects the operation outright. Choosing the right action depends on the domain semantics of the relationship.
Classification of Keys
The terminology around keys can be confusing because multiple overlapping terms exist. The following diagram and table clarify how super keys, candidate keys, primary keys, alternate keys, and foreign keys relate to one another in a Venn-diagramβstyle hierarchy.
| Key Type | Unique? | Minimal? | NOT NULL? | Cross-table? |
|---|---|---|---|---|
| Super Key | Yes | Not necessarily | Not required | No |
| Candidate Key | Yes | Yes | Not required | No |
| Primary Key | Yes | Yes | Yes (required) | No |
| Alternate Key | Yes | Yes | Varies by DBMS | No |
| Foreign Key | Not necessarily | N/A | Not required | Yes β references another table |
enrollments table might use the composite key (student_id, course_code, semester) as a natural primary key, meaning the combination of all three must be unique even though individual columns repeat.Worked Example β Designing Keys for a Library System
Suppose you are designing a database for a university library. The system must track books, members, and loans. Walk through the following steps to identify appropriate primary keys and foreign keys.
books(isbn, title, author, year_published), members(member_id, name, email, join_date), and loans(loan_id, isbn, member_id, checkout_date, return_date). Each entity becomes a table.books, the ISBN is globally unique in the real world, so {isbn} is a candidate key. For members, {member_id} is a surrogate candidate key and {email} is a natural candidate key (assuming emails are unique). For loans, {loan_id} is a surrogate candidate key, and the composite {isbn, member_id, checkout_date} could also serve as a natural candidate key.books, choose isbn (natural key, universally standardized). For members, choose member_id (surrogate, stable even if a member changes email). For loans, choose loan_id (surrogate, simpler than a three-column composite).loans table references both books and members. Therefore, loans.isbn is a foreign key referencing books.isbn, and loans.member_id is a foreign key referencing members.member_id.Surrogate vs. Natural Keys β Trade-offs
One of the most debated design decisions in relational databases is whether to use surrogate or natural primary keys. Both approaches are valid, but they carry different implications for performance, maintainability, and semantic clarity. The table below summarizes the key differences.
| Criterion | Surrogate Key | Natural Key |
|---|---|---|
| Stability | Highly stable β value never changes because it has no business meaning. | May change if the real-world attribute changes (e.g., SSN correction, email change). |
| Readability | Opaque β an integer like 47382 conveys no meaning to a human reader. | Self-documenting β ISBN, email, or country code instantly conveys identity. |
| Storage / Index Size | Typically 4β8 bytes (INT/BIGINT). Compact B-tree indexes. | Variable β a VARCHAR(255) email uses more space and produces larger indexes. |
| Join Performance | Integer comparisons are fast; foreign keys are small. | String comparisons are slower; composite natural keys amplify the overhead. |
| Schema Dependency | Adds an extra column that has no business meaning β slight denormalization. | Uses existing data β no extra column needed. |
Connection to Normalization & Advanced Constraints
Keys are not an isolated concept β they are the foundation upon which database normalization is built. The normal forms (1NF through BCNF and beyond) rely on the notion of functional dependencies, and a functional dependency X β Y means that X is a determinant β a potential key or part of one. Identifying candidate keys correctly is the prerequisite for determining whether a relation is in Second Normal Form (2NF), Third Normal Form (3NF), or Boyce-Codd Normal Form (BCNF).
| This Lesson | Advanced Topic |
|---|---|
| Primary key guarantees uniqueness within a single table. | Functional dependencies generalize this: X β Y means X determines Y, even for non-key attributes. This powers normalization theory. |
| Foreign key enforces referential integrity between two tables. | CHECK constraints, triggers, and assertions can enforce arbitrary cross-table business rules beyond simple FK references. |
| Composite keys use multiple columns. | Partial dependencies (where a non-key attribute depends on part of a composite key) are the specific violation that 2NF eliminates. |
| Surrogate keys simplify joins. | In distributed systems, UUIDs or Snowflake IDs replace auto-increment to avoid coordination overhead across shards. |
As you progress through SQL Foundations and into database design courses, you will encounter these advanced topics. The conceptual understanding of primary and foreign keys you build here will serve as the anchor point for all of them. In particular, recognizing candidate keys in a relation is the first step in any normalization procedure, and understanding referential integrity is essential for reasoning about transaction isolation, concurrency control, and distributed consistency.
Practice Problems
courses(course_code, title, department, credits) and a table sections(section_id, course_code, instructor, room, semester). Identify the primary key and any foreign keys for each table.flight_bookings table has columns: (booking_id, passenger_id, flight_number, seat_number, booking_date). Passengers are stored in passengers(passenger_id, name, passport_number), and flights in flights(flight_number, departure_city, arrival_city, departure_time). Identify all primary keys, foreign keys, and at least one alternate candidate key across these three tables. Also, what would be a suitable composite candidate key for flight_bookings if booking_id did not exist?order_items table stores individual line items and has columns (order_id, product_id, quantity, unit_price). There is no surrogate key. Determine the primary key and foreign keys. Then explain what referential action (CASCADE, SET NULL, RESTRICT) you would choose for ON DELETE on each foreign key and why.email as the primary key for a users table, arguing that it is already unique and human-readable. Three other tables (posts, comments, likes) reference this key via foreign keys. Analyze the long-term consequences of this design. Under what circumstances could it cause problems, and what alternative design would you recommend?Lesson Summary
A primary key is a candidate key β a minimal, unique attribute set β that has been designated as the official row identifier for a table. It enforces entity integrity by requiring that all component values be non-null. A foreign key is a column (or set of columns) in a child table whose values must match an existing primary key (or unique key) in a parent table, thereby enforcing referential integrity. Together, these two constraints form the backbone of the relational model, preventing orphan records and guaranteeing addressability.
When designing schemas, choose between surrogate keys (stable, compact, immutable) and natural keys (human-readable, self-documenting) based on domain requirements, and always define appropriate referential actions (CASCADE, RESTRICT, SET NULL) to handle deletions and updates gracefully. Understanding keys at a conceptual level is the gateway to normalization, functional dependencies, and sound database architecture.