Types of table relationships
One-to-One, One-to-Many, Many-to-Many
The strength of relational databases lies in how tables connect to one another. These connections enable us to maintain organized and performant database systems. Typically, the dependent table contains a foreign key column that references the primary key of the parent table, creating an enforced relationship between the two.
Relationship Categories
Relational databases support 3 fundamental relationship categories:
One-to-one
One-to-many
Many-to-many
One-to-one
A one-to-one relationship typically appears as one or more columns within a table row. For instance, an employee record will contain exactly one social_security_number.
Profile information provides another illustration of a one-to-one relationship. An employee will have exactly one department_assignment and exactly one hire_date.
One-to-Many
When discussing connections between tables, a one-to-many relationship represents the most frequently encountered pattern.
A one-to-many relationship exists when a single row in one table associates with zero or more rows in another table.
The one→many connection operates in a single direction; a row in the second table cannot associate with multiple rows in the first table!
Examples of One-to-Many Relationships
An
authorstable and abookstable. Each author has written0,1, or multiple books.A
departmentstable and anemployeestable. Eachdepartmentcontains0,1, or multiple employees working within it.
Many-to-Many
A many-to-many relationship exists when multiple rows in one table can associate with multiple rows in another table.
Examples of Many-to-Many Relationships
A
moviestable and anactorstable - Movies may feature0to many actors, and actors can appear in0to many movies.A
projectstable and anemployeestable - Employees can work on multiple projects simultaneously, and projects can have multiple employees assigned to them.
Junction Table
Junction tables facilitate many-to-many relationships between data entities in a database. As an illustration, when establishing the relationship described above between movies and actors, we would create a junction table named movie_actors that stores the primary keys from both tables being connected.
Subsequently, when we need to determine if an actor appears in a particular movie, we can query the junction table to check if the identifiers appear together in a row.
Composite Unique Constraint
When implementing specific schema rules, we may need to apply the UNIQUE constraint across multiple columns.
This configuration allows multiple rows to share the same movie_id or actor_id, but it prohibits any two rows from containing identical values for both movie_id and actor_id simultaneously.
Last updated