Sobes.tech
Junior — Middle

Can you give examples of relationship types between tables in an SQL database?

sobes.tech AI

Answer from AI

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

  1. One-to-One — each record in the first table corresponds to exactly one record in the second. For example, a Users table and a Profiles table, where each user has one profile.

  2. One-to-Many — one record in the first table corresponds to multiple records in the second. For example, an Authors table and a Books table, where one author can have many books.

  3. Many-to-Many — records in both tables can correspond to multiple records in the other table. This is usually implemented using a junction table. For example, Students and Courses tables, where a student can attend multiple courses, and a course can have many students.

Example of a many-to-many relationship with a junction table:

CREATE TABLE Students (
    student_id INT PRIMARY KEY,
    name VARCHAR(100)
);

CREATE TABLE Courses (
    course_id INT PRIMARY KEY,
    title VARCHAR(100)
);

CREATE TABLE StudentCourses (
    student_id INT,
    course_id INT,
    PRIMARY KEY (student_id, course_id),
    FOREIGN KEY (student_id) REFERENCES Students(student_id),
    FOREIGN KEY (course_id) REFERENCES Courses(course_id)
);
Can you give examples of relationship types between… - sobes.tech