What is a Relationship in a Database?
A relationship in a database defines how two or more tables are connected using keys (usually primary and foreign keys). It enables data to be linked across multiple tables without duplicating it.
⸻
Why Do We Need Relationships?
1. Data Integrity
Relationships enforce consistency. For example, an order must belong to a valid customer.
2. Avoid Data Duplication
Instead of storing customer details in every order row, we keep them in a Customers table and reference them using a CustomerID.
3. Simplifies Complex Data
Breaks down large, complex datasets into smaller, manageable parts—each with a specific focus.
⸻
How Relationships Help
• Enable JOINs, which let you pull related data together (e.g., orders + customer names).
• Support data normalization, reducing redundancy.
• Allow you to enforce constraints (like “every order must link to a real customer”).
• Improve scalability—you can add more data to one table without changing others.
Types of Relationships
Type | Description |
One-to-One | Each record in Table A matches one record in Table B (e.g., User and User Profile). |
One-to-Many | A single record in Table A can match many in Table B (e.g., Customer and Orders). |
Many-to-Many | Records in Table A can match many in Table B and vice versa, usually managed with a junction table (e.g., Students and Courses |
Real-World Example
Let’s say:
- Table A: Customers
- Table B: Orders
A relationship is built on CustomerID, allowing us to track which customer placed which order, without repeating customer details in every row.