What Are Table Relationships?
A relationship is a connection between two tables based on a common column. For example, a Customers table might relate to an Orders table through a column likecustomer_id
.
Types of Relationships
- One-to-One: Each row in one table corresponds to exactly one row in another.
- One-to-Many: One row in one table corresponds to multiple rows in another.
- Many-to-Many: Rows in one table can correspond to multiple rows in another, often handled using a join table.
Defining Relationships Using Foreign Keys
A foreign key is a column in one table that references a primary key in another table. This establishes the link between the tables.Querying Data Across Tables
Once relationships are defined, you can write queries to fetch data from multiple tables using joins. Fetch the names of customers along with their order dates:One-to-Many Relationship Example
In our example, one customer can have many orders. Thecustomer_id
column in the Orders table references the primary key in the Customers table.
Insert Sample Data
CustomerName | OrderDate |
---|---|
Raja | 2025-01-01 |
Raja | 2025-01-02 |
Understanding Referential Integrity
Foreign keys help maintain referential integrity, ensuring that:- You can’t insert a
customer_id
in orders that doesn’t exist in customers. - You can’t delete a row in customers if related rows exist in orders unless cascading actions are defined.