Database.What are the types of relationships in a database? Give examples.

In relational databases, relationships define how data in one table is connected to data in another. There are three main types of relationships:


1. 🔁 One-to-One (1:1)

➡️ One record in Table A is related to only one record in Table B, and vice versa.

✅ Example:

Table: Users

UserIDName
1Alice

Table: UserProfiles

ProfileIDUserIDBio
1011Developer
  • Each user has only one profile
  • UserID in UserProfiles is a foreign key referencing Users(UserID)

2. 🔗 One-to-Many (1:N)

➡️ One record in Table A can be related to many records in Table B,
but each record in Table B is related to only one in Table A.

✅ Example:

Table: Customers

CustomerIDName
1Alice
2Bob

Table: Orders

OrderIDCustomerIDProduct
1011Laptop
1021Phone
1032Monitor
  • One customer can place many orders
  • Each order belongs to one customer

3. 🔄 Many-to-Many (M:N)

➡️ A record in Table A can relate to many records in Table B, and vice versa.

To implement this, we use a junction table.

✅ Example:

Table: Students

StudentIDName
1Alice
2Bob

Table: Courses

CourseIDTitle
101Math
102Physics

Junction Table: StudentCourses

StudentIDCourseID
1101
1102
2101
  • Alice takes Math and Physics
  • Bob takes Math
  • This is a many-to-many relationship

🧠 Summary Table:

RelationshipDescriptionExample
One-to-OneOne row in A ↔ one row in BUser ↔ Profile
One-to-ManyOne row in A ↔ many in BCustomer ↔ Orders
Many-to-ManyMany rows in A ↔ many in B via junctionStudents ↔ Courses
This entry was posted in Без рубрики. Bookmark the permalink.