Sobes.tech
Junior — Middle

What types of relationships exist between tables in a relational database?

sobes.tech AI

Answer from AI

In relational databases, there are three main types of relationships between tables:

  1. One-to-one (1:1) — each record in the first table corresponds to exactly one record in the second table and vice versa. This is used, for example, to split data into logical parts.

  2. One-to-many (1:N) — one record in the first table corresponds to many records in the second. For example, one customer can have many orders.

  3. Many-to-many (M:N) — records in the first table can correspond to many records in the second and vice versa. To implement such a relationship, an intermediate table (linking table) is usually created, which contains foreign keys to 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)
);
What types of relationships exist between tables in a… - sobes.tech