Database Relationships and Diagrams · Lesson 18 of 112

Database One-to-Many

What you will learn

  • What a one-to-many relationship is
  • Which table holds the foreign key
  • How to list and count the children of a parent
  • Why you must not put a list in a single column

This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). It creates new tables in your browser's copy of the data; Reset data starts again.

1. One parent, many children

In a one-to-many relationship, one row in the parent table can be linked to many rows in the child table, but each child row belongs to only one parent.

  • One author writes many books (each book here has one author).
  • One customer places many orders.
  • One class has many students.

Rule: the foreign key always goes on the "many" side. A book holds author_id; an author does not hold a list of books.

authors 1 ----------< books
(one)                (many)

The < at the end is a common mark for "many" (the "crow's foot"). Lesson 3.6 explains diagrams further.

In the Shop, one customer can own many gift cards. The parent is customers; the new child table gift_cards holds the foreign key:

CREATE TABLE gift_cards (
    card_id     INTEGER PRIMARY KEY,
    customer_id INTEGER NOT NULL REFERENCES customers (customer_id),
    balance     REAL NOT NULL
);
INSERT INTO gift_cards (customer_id, balance) VALUES (1, 25.0), (1, 10.0), (2, 50.0);
(3 rows changed)

In the Bank, one branch can have many cash machines (ATMs). The parent is branches; the new child table atm_machines holds the foreign key:

CREATE TABLE atm_machines (
    atm_id    INTEGER PRIMARY KEY,
    branch_id INTEGER NOT NULL REFERENCES branches (branch_id),
    location  TEXT NOT NULL
);
INSERT INTO atm_machines (branch_id, location) VALUES (1, 'Lobby'), (1, 'Street side'), (2, 'Lobby');
(3 rows changed)

In the School, one department can have many laboratories. The parent is departments; the new child table lab_rooms holds the foreign key:

CREATE TABLE lab_rooms (
    room_id       INTEGER PRIMARY KEY,
    department_id INTEGER NOT NULL REFERENCES departments (department_id),
    name          TEXT NOT NULL
);
INSERT INTO lab_rooms (department_id, name) VALUES (1, 'Maths lab 1'), (1, 'Maths lab 2'), (2, 'Chemistry lab');
(3 rows changed)

2. Listing and counting children

SELECT c.first_name, c.last_name, g.balance
FROM customers c
JOIN gift_cards g ON g.customer_id = c.customer_id
ORDER BY g.card_id;
SELECT c.customer_id, c.last_name, COUNT(g.card_id) AS cards
FROM customers c
LEFT JOIN gift_cards g ON g.customer_id = c.customer_id
GROUP BY c.customer_id
ORDER BY cards DESC, c.customer_id
LIMIT 4;
first_name  last_name  balance
----------  ---------  -------
Vik         Ahmed         25.0
Vik         Ahmed         10.0
Wanda       Ahmed         50.0
(3 rows)

customer_id  last_name  cards
-----------  ---------  -----
          1  Ahmed          2
          2  Ahmed          1
          3  Costa          0
          4  Nair           0
(4 rows)
SELECT b.name AS branch, a.location
FROM branches b
JOIN atm_machines a ON a.branch_id = b.branch_id
ORDER BY a.atm_id;
SELECT b.branch_id, b.name, COUNT(a.atm_id) AS atms
FROM branches b
LEFT JOIN atm_machines a ON a.branch_id = b.branch_id
GROUP BY b.branch_id
ORDER BY b.branch_id;
branch     location
---------  -----------
Central    Lobby
Central    Street side
Riverside  Lobby
(3 rows)

branch_id  name        atms
---------  ----------  ----
        1  Central        2
        2  Riverside      1
        3  Harbour        0
        4  Old Town       0
        5  Airport        0
        6  University     0
(6 rows)
SELECT d.name AS department, l.name AS lab
FROM departments d
JOIN lab_rooms l ON l.department_id = d.department_id
ORDER BY l.room_id;
SELECT d.department_id, d.name, COUNT(l.room_id) AS labs
FROM departments d
LEFT JOIN lab_rooms l ON l.department_id = d.department_id
GROUP BY d.department_id
ORDER BY d.department_id;
department   lab
-----------  -------------
Mathematics  Maths lab 1
Mathematics  Maths lab 2
Science      Chemistry lab
(3 rows)

department_id  name         labs
-------------  -----------  ----
            1  Mathematics     2
            2  Science         1
            3  Languages       0
            4  Humanities      0
            5  Arts            0
            6  Computing       0
(6 rows)

The first query lists each child with its parent. The second counts children per parent. It uses a LEFT JOIN so that parents with no children yet still appear with 0. With a plain JOIN, they would vanish from the result.

3. Moving a child

To give a child to a different parent, change one value:

UPDATE gift_cards SET customer_id = 2 WHERE card_id = 2;
SELECT card_id, customer_id, balance FROM gift_cards ORDER BY card_id;
card_id  customer_id  balance
-------  -----------  -------
      1            1     25.0
      2            2     10.0
      3            2     50.0
(3 rows)
UPDATE atm_machines SET branch_id = 2 WHERE atm_id = 2;
SELECT atm_id, branch_id, location FROM atm_machines ORDER BY atm_id;
atm_id  branch_id  location
------  ---------  -----------
     1          1  Lobby
     2          2  Street side
     3          2  Lobby
(3 rows)
UPDATE lab_rooms SET department_id = 2 WHERE room_id = 2;
SELECT room_id, department_id, name FROM lab_rooms ORDER BY room_id;
room_id  department_id  name
-------  -------------  -------------
      1              1  Maths lab 1
      2              2  Maths lab 2
      3              2  Chemistry lab
(3 rows)

The second row now belongs to another parent. Nothing else changed.

4. The wrong way: a list in one column

Beginners sometimes store all children in a single text column on the parent:

CREATE TABLE bad_customers (customer TEXT, cards TEXT);
INSERT INTO bad_customers VALUES ('Vik Ahmed', '25.0,10.0');
SELECT * FROM bad_customers;
SELECT customer FROM bad_customers WHERE cards = '10.0';
SELECT customer FROM bad_customers WHERE cards LIKE '%10.0%';
customer   cards
---------  ---------
Vik Ahmed  25.0,10.0
(1 row)

customer
--------
(0 rows)

customer
---------
Vik Ahmed
(1 row)

Asking "who has a card of 10.0?" with = finds nothing, because the column holds the whole text 25.0,10.0. The LIKE search works here, but it would also match a card of 110.0.

CREATE TABLE bad_branches (branch TEXT, atms TEXT);
INSERT INTO bad_branches VALUES ('Central', 'Lobby,Street side');
SELECT * FROM bad_branches;
SELECT branch FROM bad_branches WHERE atms = 'Street side';
SELECT branch FROM bad_branches WHERE atms LIKE '%Street side%';
branch   atms
-------  -----------------
Central  Lobby,Street side
(1 row)

branch
------
(0 rows)

branch
-------
Central
(1 row)

Asking "which branch has the Street side machine?" with = finds nothing, because the column holds the whole text Lobby,Street side. The LIKE search works here, but it would also match a machine called Street side north.

CREATE TABLE bad_departments (department TEXT, labs TEXT);
INSERT INTO bad_departments VALUES ('Mathematics', 'Maths lab 1,Maths lab 2');
SELECT * FROM bad_departments;
SELECT department FROM bad_departments WHERE labs = 'Maths lab 2';
SELECT department FROM bad_departments WHERE labs LIKE '%Maths lab 2%';
department   labs
-----------  -----------------------
Mathematics  Maths lab 1,Maths lab 2
(1 row)

department
----------
(0 rows)

department
-----------
Mathematics
(1 row)

Asking "which department has Maths lab 2?" with = finds nothing, because the column holds the whole text Maths lab 1,Maths lab 2. The LIKE search works here, but it would also match a lab called Maths lab 20.

The database cannot check that each listed name exists, count them reliably or index them. One value per column, one row per fact: that is why we use a child table.

Worked example: where does the foreign key go?

A clinic wants to store patients and their appointments. A patient can have many appointments; each appointment is for one patient.

Step Decision
Which side is "many"? appointments
So the foreign key is in appointments.patient_id, pointing to patients.id
Tables patients(id, name) and appointments(id, patient_id, day)

Names and clinic are made up.

Common mistakes

  • Putting the foreign key on the "one" side. It belongs on the "many" side.
  • Storing a list of ids in one column ("1,2,3").
  • Using a plain JOIN when you want parents with zero children; use LEFT JOIN.
  • Calling it one-to-many when a child can have two parents. That is many-to-many (lesson 3.4).

Key takeaways

  • One-to-many: one parent row, many child rows, each child has one parent.
  • The foreign key goes in the child ("many") table.
  • JOIN lists children; LEFT JOIN with COUNT also shows parents with none.
  • Moving a child means changing one foreign key value.
  • Never store a list in one column; use a child table.

Practice

1. Which table holds the foreign key in "one class has many students"?

Show answer

students (the "many" side), with a column such as class_id.

2. Why did some parents show 0 in the count query?

Show answer

A LEFT JOIN keeps every parent, and COUNT(child.id) counts only real child rows, so a parent with none gets 0.

3. How do you move a child row to a different parent?

Show answer

Change its foreign key, for example UPDATE gift_cards SET customer_id = 2 WHERE card_id = 2.

4. Give two problems with storing Rivers,Hills in one column.

Show answer

Searching with = fails, and the database cannot check, count or index each title. A text search may also match the wrong rows.

5. Draw the diagram line for "one customer has many orders".

Show answer

customers 1 ----------< orders

6. Name another one-to-many example from daily life.

Show answer

For example, one mother has many children in a family record, or one shop has many sales.