Reading history

Table Relationships: One-to-One, One-to-Many and Many-to-Many

5 min read 0 views

Learn database table relationships with SQL examples: one-to-many foreign keys, one-to-one tables, many-to-many junction tables and composite primary keys.

Real data is connected. A student belongs to a department, takes several courses, and has one library card. When you design a database, each of these connections becomes a relationship between tables, built with primary and foreign keys. There are three kinds: one-to-one, one-to-many and many-to-many. Recognising which one you have tells you exactly how to build the tables.

In this lesson you will learn

  • One-to-many relationships, the most common kind
  • One-to-one relationships and when to use them
  • Many-to-many relationships with a junction table
  • Composite primary keys that stop duplicate links
  • How to query each relationship with joins

You should know joins and foreign keys. The examples use the students, departments, courses and enrollments tables from earlier lessons.

One-to-Many and One-to-One

-- One-to-many: each student belongs to one department,
-- and a department has many students
SELECT d.name AS department, COUNT(s.id) AS students
FROM departments d
LEFT JOIN students s ON s.dept = d.code
GROUP BY d.code
ORDER BY students DESC;

-- One-to-one: each student has at most one library card
CREATE TABLE library_cards (
    student_id INTEGER PRIMARY KEY REFERENCES students(id),
    card_no    TEXT UNIQUE NOT NULL,
    expires    TEXT
);
INSERT INTO library_cards VALUES (1, 'LC-0001', '2027-06-30'), (3, 'LC-0002', '2027-06-30');

SELECT s.name, c.card_no
FROM students s
JOIN library_cards c ON c.student_id = s.id;

Output

+-------------------------+----------+
| department              | students |
+-------------------------+----------+
| Computer Science        | 4        |
| Business Administration | 2        |
| Electrical Engineering  | 2        |
| Mechanical Engineering  | 0        |
+-------------------------+----------+
(4 rows)

+--------+---------+
| name   | card_no |
+--------+---------+
| Nusrat | LC-0001 |
| Tania  | LC-0002 |
+--------+---------+
(2 rows)
  • One-to-many: one department has many students, but each student has one department. Build it by putting the foreign key on the “many” side: students.dept refers to departments.code.
  • The LEFT JOIN keeps departments with no students, so Mechanical Engineering appears with 0.
  • One-to-one: each student has at most one library card, and each card belongs to one student. Making student_id the primary key of library_cards enforces “at most one card per student”.
  • Use a separate one-to-one table when the extra columns are optional (most students have no card), rarely used, or need different access rights. Otherwise just add the columns to the main table.

Many-to-Many with a Junction Table

-- Many-to-many: students take many courses, courses have many students.
-- The enrollments table is the junction (link) table between them.
SELECT s.name, c.title, e.marks
FROM enrollments e
JOIN students s ON s.id = e.student_id
JOIN courses  c ON c.id = e.course_id
WHERE c.dept = 'CSE'
ORDER BY c.title, e.marks DESC;

-- Number of students in each course
SELECT c.title, COUNT(e.student_id) AS students, MAX(e.marks) AS top_mark
FROM courses c
LEFT JOIN enrollments e ON e.course_id = c.id
GROUP BY c.id
ORDER BY students DESC, c.title;

-- A well-designed junction table: composite primary key stops duplicates
CREATE TABLE enrollments_v2 (
    student_id INTEGER REFERENCES students(id),
    course_id  INTEGER REFERENCES courses(id),
    marks      INTEGER,
    PRIMARY KEY (student_id, course_id)
);
INSERT INTO enrollments_v2 VALUES (1, 101, 88);
-- fails: Nusrat is already enrolled in course 101
INSERT INTO enrollments_v2 VALUES (1, 101, 90);

Output

+--------+-----------------+-------+
| name   | title           | marks |
+--------+-----------------+-------+
| Tania  | Data Structures | 95    |
| Nusrat | Data Structures | 88    |
| Nusrat | Databases       | 92    |
| Tania  | Databases       | 90    |
| Mitu   | Databases       | 76    |
+--------+-----------------+-------+
(5 rows)

+-----------------+----------+----------+
| title           | students | top_mark |
+-----------------+----------+----------+
| Databases       | 3        | 92       |
| Circuit Theory  | 2        | 81       |
| Data Structures | 2        | 95       |
| Marketing       | 2        | 85       |
+-----------------+----------+----------+
(4 rows)

Error: UNIQUE constraint failed: enrollments_v2.student_id, enrollments_v2.course_id
  • Many-to-many: a student takes many courses, and a course has many students. A single foreign key cannot express this, because neither side has just one partner.
  • The solution is a junction table (also called a link, bridge or associative table). Each row of enrollments links one student to one course, and it is also the natural place for facts about the pair, such as marks.
  • Querying it takes two joins: junction to students, and junction to courses.
  • The composite primary key (student_id, course_id) allows each student–course pair only once, so the second enrollment of Nusrat in course 101 is rejected.

Relationship Types at a Glance

RelationshipExampleHow to build it
One-to-oneStudent – library cardForeign key that is also UNIQUE or the primary key
One-to-manyDepartment – studentsForeign key on the “many” side
Many-to-manyStudents – coursesJunction table with two foreign keys

In entity-relationship (ER) diagrams these are often written as 1:1, 1:N and M:N. Splitting data into related tables this way is the heart of database normalization.

Common Mistakes

  1. Storing lists in one column, such as courses = '101,102'. It cannot be joined, indexed or validated. Use a junction table.
  2. Adding course1, course2, course3 columns, which limits the number of courses and makes queries awkward.
  3. Putting the foreign key on the wrong side of a one-to-many relationship.
  4. Leaving the junction table without a unique key, so the same link can be stored twice.

Practice Exercises

Exercise 1. Design tables for books and authors, where a book can have several authors and an author can write several books.

Show answer
CREATE TABLE authors (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE books   (id INTEGER PRIMARY KEY, title TEXT NOT NULL);
CREATE TABLE book_authors (
    book_id   INTEGER REFERENCES books(id),
    author_id INTEGER REFERENCES authors(id),
    PRIMARY KEY (book_id, author_id)
);

Exercise 2. List every student with the number of courses they take, including students with none.

Show answer
SELECT s.name, COUNT(e.course_id) AS courses
FROM students s
LEFT JOIN enrollments e ON e.student_id = s.id
GROUP BY s.id, s.name
ORDER BY courses DESC;

COUNT(e.course_id) counts 0 for students with no match, whereas COUNT(*) would count 1.

Frequently Asked Questions

Should a junction table have its own id column?

It is optional. A composite primary key on the two foreign keys is enough and prevents duplicates. If you add a surrogate id, still add a UNIQUE constraint on the pair.

How do I name a junction table?

Use either a real-world noun such as enrollments or memberships, or join the two table names, such as book_authors. Pick one style and use it everywhere.

Summary

  • One-to-many: foreign key on the “many” side.
  • One-to-one: a foreign key that is also unique.
  • Many-to-many: a junction table with two foreign keys and a composite key.
  • Never store lists of ids in a single column.

Next: SQL UPSERT: Insert or Update.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *