Database DesignRelationships & ER diagramsLesson 19 / 69

One-to-many

Fill-gap25 min

One-to-many

One-to-many is the workhorse of data design: one user writes many diagrams; one chapter holds many lessons. On the many side you keep a column pointing back:

CREATE TABLE diagrams (
  id bigint PRIMARY KEY,
  user_id bigint NOT NULL REFERENCES users(id),
  name varchar NOT NULL
);

The REFERENCES clause is a promise the database keeps for you: no diagram may point at a user that does not exist. That single constraint deletes a whole class of bugs before they happen.

Exercise

Sketch users→diagrams→tables: three one-to-many chains from an app you know. Write the FK column for each arrow.