Careeroza
Relationships
One-to-Many (1:N)
The most common relationship: one customer has many orders, each order belongs to one customer. Put the foreign key on the "many" side.
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
CustomerID INT NOT NULL REFERENCES Customers(CustomerID)
);One-to-One (1:1)
Each row matches at most one row in the other table, e.g. an employee and their sensitive HR details, kept separately for security. Make the foreign key also the primary key (or UNIQUE).
CREATE TABLE EmployeePrivate (
EmployeeID INT PRIMARY KEY REFERENCES Employees(EmployeeID),
PAN VARCHAR(10),
BankAccount VARCHAR(30)
);Many-to-Many (M:N)
An order contains many products and a product appears in many orders. Relational tables cannot store this directly; use a junction (bridge) table with two foreign keys. OrderDetails in the demo database is one.
Example
Students and courses:
CREATE TABLE Students (StudentID INT PRIMARY KEY, Name TEXT);
CREATE TABLE Courses (CourseID INT PRIMARY KEY, Title TEXT);
CREATE TABLE Enrollments (
StudentID INT REFERENCES Students(StudentID),
CourseID INT REFERENCES Courses(CourseID),
EnrolledOn DATE,
PRIMARY KEY (StudentID, CourseID)
);
INSERT INTO Students VALUES (1, 'Asha'), (2, 'Vikram');
INSERT INTO Courses VALUES (10, 'SQL Basics'), (20, 'Data Modeling');
INSERT INTO Enrollments VALUES (1, 10, '2024-06-01'), (1, 20, '2024-06-05'), (2, 10, '2024-06-02');
SELECT s.Name, c.Title
FROM Enrollments e
JOIN Students s ON s.StudentID = e.StudentID
JOIN Courses c ON c.CourseID = e.CourseID
ORDER BY s.Name;Result: 3 rows
| Name | Title |
|---|---|
| Asha | SQL Basics |
| Asha | Data Modeling |
| Vikram | SQL Basics |