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:
-
One-to-One — each record in the first table corresponds to exactly one record in the second. For example, a
Userstable and aProfilestable, where each user has one profile. -
One-to-Many — one record in the first table corresponds to multiple records in the second. For example, an
Authorstable and aBookstable, where one author can have many books. -
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,
StudentsandCoursestables, 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)
);