Resources | Subject Notes | Information Communication Technology ICT | Lesson Plan
This section focuses on understanding and implementing relationships between tables in a database. Relationships are crucial for organizing data efficiently and avoiding redundancy. We will explore different types of relationships and how to define them using primary and foreign keys.
A primary key is a unique identifier for each record in a table. It ensures that every record can be distinguished from all others. A foreign key is a field in one table that refers to the primary key of another table. This is how we link tables together.
There are three main types of relationships between tables:
Consider a Customers table and an Orders table. A customer can place multiple orders, but each order belongs to only one customer. This is a one-to-many relationship.
Table | Columns | Primary Key | Foreign Key |
---|---|---|---|
Customers | CustomerID, Name, Address, Phone | CustomerID | |
Orders | OrderID, CustomerID, OrderDate, TotalAmount | OrderID | CustomerID (references Customers.CustomerID) |
In this example, the CustomerID in the Orders table is a foreign key that references the CustomerID (primary key) in the Customers table.
Consider a Students table and a Courses table. A student can enroll in multiple courses, and a course can have multiple students. This is a many-to-many relationship. To represent this, we need a StudentCourses linking table.
The StudentCourses table would have two foreign keys, one referencing Students and one referencing Courses.
Table | Columns | Primary Key | Foreign Key |
---|---|---|---|
Students | StudentID, Name, Major | StudentID | |
Courses | CourseID, CourseName, Credits | CourseID | |
StudentCourses | StudentID, CourseID, Grade | StudentID, CourseID (composite key) |
The StudentCourses table acts as a bridge between the Students and Courses tables.
Database systems like MySQL, PostgreSQL, and SQLite allow you to define relationships between tables using foreign key constraints. These constraints ensure data integrity by preventing actions that would violate the relationships.
For example, a foreign key constraint on the Orders table would prevent you from adding an order with a CustomerID that does not exist in the Customers table.
When designing database relationships, consider the following: