Junior — Middle
Can you list the types of relationships that exist between tables in a database?
sobes.tech AI
Answer from AI
There are three main types of relationships between tables in databases:
-
One-to-One — each record in the first table corresponds to exactly one record in the second table and vice versa. Used when data is logically separated but directly related.
-
One-to-Many — one record in the first table corresponds to many records in the second. For example, one user can have many orders.
-
Many-to-Many — records in the first table can correspond to many records in the second and vice versa. Implemented through an intermediate linking table that contains foreign keys of both tables.
Example of a "many-to-many" relationship:
-- Students table
CREATE TABLE Students (
StudentID INT PRIMARY KEY,
Name VARCHAR(100)
);
-- Courses table
CREATE TABLE Courses (
CourseID INT PRIMARY KEY,
Title VARCHAR(100)
);
-- Intermediate table for many-to-many relationship
CREATE TABLE StudentCourses (
StudentID INT,
CourseID INT,
PRIMARY KEY (StudentID, CourseID),
FOREIGN KEY (StudentID) REFERENCES Students(StudentID),
FOREIGN KEY (CourseID) REFERENCES Courses(CourseID)
);
These types of relationships form the basis of relational data modeling.