Table
Relationships
Understand how database tables connect through one-to-one, one-to-many, and many-to-many relationships: the foundation of relational database design.
What Are Table Relationships?
In a relational database, data is organized into tables (also called relations). Each table stores information about one type of entity: students, courses, orders, or products. A table relationship describes how rows in one table connect to rows in another table.
Primary Keys and Foreign Keys
Why Relationships Matter
The Three Relationship Types
One-to-One Relationship
One-to-Many Relationship
Many-to-Many Relationship
Key Distinction
| One-to-One | One-to-Many | Many-to-Many | |
|---|---|---|---|
| FK Location | Either table | "Many" side | Junction table |
| FK Unique? | Yes | No | No (composite PK) |
| Tables Needed | 2 | 2 | 3 (includes junction) |
| Common Example | User ↔ Profile | Customer ↔ Orders | Students ↔ Courses |
| Frequency | Rare | Most common | Common |
The Junction Table
Relational databases have no built-in "many-to-many" link. Instead, we create a third table (the junction table, also called a bridge table or linking table) that sits between the two related tables.
How to Identify the Type
Example: Library System
Scenario: A library has Authors and Books. One author can write many books, but each book is written by exactly one author.
Example: School Schedule
Scenario: Teachers and Classes. A teacher can teach many classes, and a class can be taught by many teachers (team-teaching, substitutes).
SQL in Action
Here is how you create a one-to-many relationship between Customers and Orders in SQL:
customer_id INT PRIMARY KEY,
name VARCHAR(100)
);
CREATE TABLE Orders (
order_id INT PRIMARY KEY,
customer_id INT,
total DECIMAL(10,2),
FOREIGN KEY (customer_id)
REFERENCES Customers(customer_id)
);
Common Mistakes
Summary Table
| Concept | Key Point |
|---|---|
| Primary Key | Uniquely identifies each row |
| Foreign Key | References another table's PK |
| One-to-One | FK with UNIQUE constraint |
| One-to-Many | FK on the "many" side, no UNIQUE |
| Many-to-Many | Junction table with two FKs |
| Junction Table | Composite PK from both FKs |
Question 1 of 5
A Customers table and an Orders table are related so that each customer can place many orders, but each order belongs to one customer. What type of relationship is this?
Question 2 of 5
In a one-to-one relationship, what constraint must be placed on the foreign key column?
Question 3 of 5
Students can enroll in many Courses, and each course can have many students. How should this be modeled in a relational database?
Question 4 of 5
In a one-to-many relationship between Departments and Employees, where should the foreign key be placed?
Question 5 of 5
A Person has exactly one Passport, and each passport belongs to exactly one person. A developer creates the relationship but forgets the UNIQUE constraint on the FK. What is the consequence?