-- The "One" side
CREATE TABLE Department (
id INT PRIMARY KEY,
name VARCHAR(50)
);
-- The "Many" side holds the Foreign Key pairing it to the parent.
CREATE TABLE Employee (
id INT PRIMARY KEY,
name VARCHAR(50),
department_id INT,
FOREIGN KEY (department_id) REFERENCES Department(id)
);
In relational databases, collections are NOT stored inside rows. Instead, child rows hold a Foreign Key to the parent's Primary Key.
-- Base Tables
CREATE TABLE Student (id INT PRIMARY KEY, name VARCHAR(50));
CREATE TABLE Course (id INT PRIMARY KEY, title VARCHAR(50));
-- Junction Table bridging the M:N gap
CREATE TABLE Enrollment (
student_id INT,
course_id INT,
grade VARCHAR(2),
PRIMARY KEY (student_id, course_id),
FOREIGN KEY (student_id) REFERENCES Student(id),
FOREIGN KEY (course_id) REFERENCES Course(id)
);
A pure many-to-many relationship cannot be represented directly in SQL without an intermediate junction table consisting of multiple Foreign Keys.
-- Putting all parent and child attributes into one wide table.
CREATE TABLE Vehicle (
id INT PRIMARY KEY,
type VARCHAR(20), -- Discriminator Column ('CAR' or 'TRUCK')
top_speed INT, -- Parent attribute
num_doors INT, -- 'CAR' only attribute (Nullable)
cargo_capacity INT -- 'TRUCK' only attribute (Nullable)
);
All subclasses mapped to one table. Requires a discriminator column. Subclass-specific columns must be nullable. Efficient for polymorphic queries but breaks normalization.
-- Parent table holds generic data
CREATE TABLE Vehicle (
id INT PRIMARY KEY,
top_speed INT
);
-- Child table holds specific data AND links back to Parent PK (as its own PK)
CREATE TABLE Car (
vehicle_id INT PRIMARY KEY,
num_doors INT,
FOREIGN KEY (vehicle_id) REFERENCES Vehicle(id)
);
Clean, highly normalized DB structure. However, fetching a full Car object requires a SQL JOIN operation between the Vehicle and Car tables.