01 / 21

Primary & Foreign
Keys

Learn how to uniquely identify rows with primary keys and connect tables with foreign keys: the foundation of relational database design.

SQL

What Is a Key?

In a relational database, a key is a column (or set of columns) used to identify and relate rows in tables. Keys enforce data integrity and make it possible to connect information across multiple tables.

Identify
Each row must be distinguishable from every other row.
Relate
Tables need a mechanism to reference rows in other tables.
Constrain
Keys prevent invalid or duplicate data from entering the database.

The Primary Key

A primary key (PK) is a column (or combination of columns) whose values uniquely identify every row in a table. No two rows may share the same primary key value, and it can never be NULL.

student_id name grade 1 Alice 10 2 Bob 11 3 Carol 10 PK: unique, not null

The Foreign Key

A foreign key (FK) is a column in one table that references the primary key of another table. It creates a link between two tables and enforces referential integrity: you cannot insert a value that does not exist in the referenced table.

students student_id (PK) name grade email enrollments enrollment_id (PK) student_id (FK) course_id (FK) enrolled_date enrollments.student_id references students.student_id

Two Fundamental Rules

1
Entity Integrity: A primary key must be unique and never NULL. Every row must be identifiable.
2
Referential Integrity: A foreign key value must match an existing primary key in the referenced table, or be NULL (if allowed).

Visualizing a One-to-Many Relationship

teachers teacher_id (PK) name department hire_date 1 courses course_id (PK) teacher_id (FK) title credits N One teacher teaches many courses The FK (teacher_id) lives on the "many" side

Primary Key vs Foreign Key

Property Primary Key Foreign Key
Purpose Uniquely identify each row Reference a row in another table
Uniqueness Must be unique Can repeat (many rows may reference the same PK)
NULL allowed? No, never Sometimes (if the relationship is optional)
Per table Exactly one PK Zero or many FKs
Enforces Entity integrity Referential integrity

How to Choose a Primary Key

1
Uniqueness: Can the column guarantee a different value for every row, now and in the future?
2
Stability: Will the value change over time? A good PK value never changes. Names and emails are poor choices.
3
Simplicity: A single-column integer ID is easier to index and join than a multi-column composite key.
4
Non-NULL: The column must be mandatory. If it could ever be unknown, it cannot serve as a PK.

Defining a Foreign Key Relationship

1
Identify the parent table: Which table holds the data being referenced? Its PK is the target.
2
Add an FK column to the child table: Give it the same data type as the parent's PK.
3
Declare the constraint: Use REFERENCES to tell the database which PK the FK points to.
CREATE TABLE courses ( course_id INT PRIMARY KEY, title VARCHAR(100), teacher_id INT, FOREIGN KEY (teacher_id) REFERENCES teachers(teacher_id) );

Example 1: School Database

A school tracks students and the clubs they join. A student can join many clubs, and a club can have many students. This is a many-to-many relationship: it requires a junction table.

students student_id (PK) name grade student_clubs id (PK) student_id (FK) club_id (FK) clubs club_id (PK) club_name advisor Junction table resolves many-to-many Each row in student_clubs links one student to one club

Example 2: E-Commerce Orders

An online store has customers, orders, and products. Each order belongs to one customer, and each order contains many products (via order_items).

customers customer_id (PK) name, email orders order_id (PK) customer_id (FK) order_date, total order_items item_id (PK) order_id (FK) product_id (FK) products product_id (PK) name, price

Example 3: Full SQL Syntax

Here is the complete SQL to create the customers and orders tables with a foreign key constraint:

-- Parent table first CREATE TABLE customers ( customer_id INT PRIMARY KEY, name VARCHAR(100) NOT NULL, email VARCHAR(255) UNIQUE ); -- Child table references parent CREATE TABLE orders ( order_id INT PRIMARY KEY, customer_id INT NOT NULL, order_date DATE, FOREIGN KEY (customer_id) REFERENCES customers(customer_id) );

Composite Primary Keys

Sometimes no single column is unique on its own. A composite primary key uses two or more columns together. The combination must be unique, even if individual values repeat.

CREATE TABLE student_clubs ( student_id INT, club_id INT, join_date DATE, PRIMARY KEY (student_id, club_id), FOREIGN KEY (student_id) REFERENCES students(student_id), FOREIGN KEY (club_id) REFERENCES clubs(club_id) );

Natural vs Surrogate Keys

Natural Key
A column with real-world meaning: Social Security Number, ISBN, email address. Meaningful but risky: values can change or collide.
Surrogate Key
A system-generated value with no business meaning: auto-increment integer, UUID. Stable, simple, and universally unique.

Common Mistakes

✕ Using name as PK
Names are not unique (two "John Smith" students) and can change. Always use an ID column.
✕ Mismatched data types
The FK column must match the PK's data type exactly. An INT FK cannot reference a VARCHAR PK.
✕ FK on the wrong table
In a one-to-many, the FK goes on the "many" side. Putting it on the "one" side breaks the relationship.

Summary at a Glance

Concept Key Fact SQL Keyword
Primary Key Unique + NOT NULL per table PRIMARY KEY
Foreign Key References another table's PK FOREIGN KEY ... REFERENCES
Composite Key Two+ columns forming PK together PRIMARY KEY (a, b)
Surrogate Key Auto-generated ID, no business meaning AUTO_INCREMENT / SERIAL
Referential Integrity FK value must exist as a PK REFERENCES table(col)

Question 1 of 5

Which property is required of a primary key column?

Question 2 of 5

In a one-to-many relationship between departments (one) and employees (many), where should the foreign key be placed?

Question 3 of 5

A student_courses table has columns student_id and course_id. The same student should not enroll in the same course twice. What is the best primary key?

Question 4 of 5

What happens if you try to insert a row into orders with a customer_id that does not exist in the customers table?

Question 5 of 5

Why is email generally a poor choice for a primary key, even though emails are unique?