Be able to create relationships between tables
📚 18 Databases – Creating Relationships Between Tables
What is a Relationship?
A relationship is a way to link data in one table to data in another. Think of it like a family tree – each person (row) is connected to their parents and children (other rows in different tables). In databases, we use keys to make those connections.
Key Types
- Primary Key (PK) – unique identifier for each row. Like a student’s unique ID.
- Foreign Key (FK) – a field that links to a PK in another table. Like a student’s class ID that points to the Classes table.
Example Scenario
We’ll model a simple school system with two tables: Students and Classes.
| Table | Columns | Notes |
|---|---|---|
| Students |
StudentID (PK),FirstName,LastName,ClassID (FK)
|
Each student belongs to one class. |
| Classes |
ClassID (PK),ClassName,TeacherName
|
Each class can have many students. |
Step‑by‑Step: Adding a Relationship
- Define the
Classestable first so thatClassIDexists. - Create the
Studentstable and addClassIDas a column. - Set
ClassIDinStudentsas a Foreign Key that referencesClasses.ClassID. - When inserting a student, ensure the
ClassIDvalue matches an existing class. - Use queries like:
SELECT s.FirstName, s.LastName, c.ClassName FROM Students s JOIN Classes c ON s.ClassID = c.ClassID;
Visual Analogy
Imagine a school bus (Classes) that carries many students. Each student has a bus ticket (ClassID) that tells the bus which route they’re on. The bus ticket is the foreign key linking the student to the bus.
Quick Quiz
- What is the purpose of a
Primary Key? - Which column in the
Studentstable is theForeign Key? - Write a simple SQL statement to find all students in the “Biology 101” class.
Revision
Log in to practice.
3 views
0 suggestions