Skip to content
Visual explainer 3h to learn 4 steps

Entities, relationships & ER diagrams

Turn requirements into tables with one-to-many and many-to-many relationships.

By Invicly Tech, , in SQL & PostgreSQL. About 11 minutes to read.

Topic 13 of 30

In short

Data modelling turns requirements into tables. Nouns become entities (tables), their facts become columns, and relationships become foreign keys, with a join table for many-to-many links.

Explained simply

Before you write any SQL, you decide what the database should remember. That plan is called a data model. You read the requirements and look for the important nouns: customer, order, product, course, student. Each of these kinds of thing usually becomes a table. The facts about it (a name, a price, a date) become columns.

Then you ask how the things connect. One customer places many orders, but each order belongs to one customer: that is one-to-many. A student takes many courses, and a course has many students: that is many-to-many. The answer to "how many?" on each side decides where the links go.

Links are stored as foreign keys: a column that holds the id of a row in another table. For one-to-many, the id goes on the many side. For many-to-many, you add a small extra table in the middle that holds pairs of ids.

An ER diagram (entity-relationship diagram) is the picture of this plan: boxes for tables, lines for relationships, and small symbols at the line ends that show one or many. It is cheap to change a drawing and expensive to change a live database, so draw first.

Press Play on a diagram to walk through it one step at a time.

MapLibrary schema
library database
  • authors
    • id PK
    • name
  • books
    • id PK
    • title
    • published_year
  • book_authors (join)
    • book_id FK
    • author_id FK
    • PK (book_id, author_id)
  • members
    • id PK
    • email UNIQUE
  • loans
    • id PK
    • book_id FK
    • member_id FK
    • due_on
CompareWhere the keys go for each cardinality
One-to-one
  • users and user_profiles
  • FK on either side
  • Add UNIQUE on the FK
  • Or share the same primary key
One-to-many
  • customers and orders
  • FK on the many side
  • orders.customer_id
  • Index the FK column
Many-to-many
  • students and courses
  • New join table
  • enrolments(student_id, course_id)
  • Composite PK on both ids

In depth

From requirements to entities and attributes

Start with sentences from the people who will use the app, for example: "A customer places orders. An order contains several products. Each product belongs to one category." Underline the nouns. Nouns that have their own facts and their own life become entities (tables). Nouns that only describe something become attributes (columns).

A useful test: does it need its own id, and can it exist on its own? A category has a name and many products, so it is an entity. A colour of a product is usually just a column. An address is a judgement call: if customers have several saved addresses, it becomes its own table.

Also ask what must be remembered over time. If prices change, an order line must store the price that was paid, not just point to today's price.

  • Nouns with their own facts become tables
  • Describing words become columns
  • Verbs (places, contains, teaches) become relationships
  • Ask: can it exist alone, and can there be several?
FlowFrom a requirement to tables
  1. 1
    Collect sentences

    Short statements from users and the product owner

  2. 2
    Find the nouns

    Candidates for entities and attributes

  3. 3
    Find the verbs

    Candidates for relationships

  4. 4
    Ask how many

    One or many on each side of each verb

  5. 5
    Place the keys

    FK on the many side, join table for many-to-many

  6. 6
    Draw and review

    Check every requirement can be answered

One-to-many and one-to-one in practice

One-to-many is the most common link. The child table gets a column such as customer_id that references customers(id). Add NOT NULL if every order must have a customer, and leave it nullable if the link is optional. Remember to index that column, because Postgres does not do it for you and you will often look up "all orders of customer 42".

One-to-one links are rarer. Use them to split rarely used or sensitive columns into a second table, such as user_profiles next to users. The child gets a foreign key plus a UNIQUE constraint, or it simply uses the parent's id as its own primary key. If two tables are always read together and always one-to-one, they probably belong in one table.

A table can also point to itself. employees.manager_id references employees(id) to build an org chart.

  • FK column + NOT NULL = the link is required
  • FK + UNIQUE = one-to-one
  • Self reference: a row points to another row in the same table

Many-to-many and join tables that carry data

A relational column holds one value, so you cannot store "all the courses of this student" in one cell without breaking the rules. Instead, a join table (also called a junction or link table) holds one row per pair, for example enrolments(student_id, course_id). A composite primary key on both columns stops the same pair being added twice.

Join tables often grow their own facts. An enrolment has an enrolled_at date and a grade. An order line has a quantity and the unit price at the time of purchase. When that happens, the join table becomes a real entity with a meaningful name (enrolments, order_items), and that is a good sign.

To find all courses for a student, you join three tables: students to enrolments to courses.

Reading and drawing an ER diagram

Most teams use crow's foot notation. Each table is a box listing its columns, with PK and FK marked. A line joins two related tables. At each end of the line, a single bar means "one", a three-pronged crow's foot means "many", and a small circle means "zero is allowed" (optional). So a line from customers (bar) to orders (circle plus crow's foot) reads: one customer has zero or many orders.

You can draw by hand, but tools save time. dbdiagram.io turns a short text description into a diagram, pgAdmin has an ERD Tool, DBeaver can draw a diagram from an existing database, and Mermaid erDiagram blocks render inside many Markdown viewers, so the diagram can live in Git next to your code.

CompareLine-end symbols in crow's foot notation
Exactly one
  • Two short bars
  • The row must exist
  • orders to customers
  • FK is NOT NULL
Zero or one
  • Circle and a bar
  • Optional single link
  • users to user_profiles
  • FK + UNIQUE, nullable
Zero or many
  • Circle and a crow's foot
  • Any number, even none
  • customers to orders
  • The FK lives on this side

Learn it in 4 short steps

About 45m each. Track them with a timer in your plan.

  1. 1
    Identify entities and attributes~45m
  2. 2
    Model one-to-many relationships~45m
  3. 3
    Model many-to-many with join tables~45m
  4. 4
    Draw an ER diagram~45m

Key points

  • One-to-many: put the foreign key on the "many" side (loans.member_id).
  • Many-to-many: add a join table holding both foreign keys.
  • Each table should describe one kind of thing.
  • An ER diagram shows tables as boxes and relationships as lines.

Key terms

Tap a card to flip it. 0/5 known

Examples

sql
CREATE TABLE authors (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name text NOT NULL);
CREATE TABLE books   (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, title text NOT NULL);

CREATE TABLE book_authors (
  book_id   bigint REFERENCES books(id)   ON DELETE CASCADE,
  author_id bigint REFERENCES authors(id) ON DELETE CASCADE,
  PRIMARY KEY (book_id, author_id)
);

Modelling a small online course site

Requirements: "Instructors create courses. Students enrol in many courses. Each enrolment records the date and a final grade." Step 1: nouns give instructors, courses and students. Step 2: one instructor teaches many courses, so courses gets instructor_id. Step 3: students and courses are many-to-many, so add enrolments. Step 4: the date and grade describe the pair, not the student or the course, so they go on enrolments.

sql
CREATE TABLE instructors (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name text NOT NULL);
CREATE TABLE students    (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, email text NOT NULL UNIQUE);
CREATE TABLE courses (
  id            bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  instructor_id bigint NOT NULL REFERENCES instructors(id),
  title         text NOT NULL
);
CREATE INDEX ON courses (instructor_id);
CREATE TABLE enrolments (
  student_id  bigint REFERENCES students(id),
  course_id   bigint REFERENCES courses(id),
  enrolled_on date NOT NULL DEFAULT current_date,
  grade       smallint CHECK (grade BETWEEN 0 AND 100),
  PRIMARY KEY (student_id, course_id)
);

Fixing a comma-separated tags column

A blog stores tags as text like 'sql,postgres,tips' in posts.tags. Finding all posts tagged sql needs slow LIKE searches, typos create near-duplicate tags, and renaming a tag means editing every post. Step 1: create a tags table with a unique name. Step 2: create post_tags as a join table. Step 3: copy the data across with string_to_table, which splits text into rows. Step 4: drop the old column after the app reads the new tables.

sql
CREATE TABLE tags (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name text NOT NULL UNIQUE);
CREATE TABLE post_tags (
  post_id bigint REFERENCES posts(id) ON DELETE CASCADE,
  tag_id  bigint REFERENCES tags(id)  ON DELETE CASCADE,
  PRIMARY KEY (post_id, tag_id)
);
INSERT INTO tags (name)
SELECT DISTINCT trim(t.tag) FROM posts p, string_to_table(p.tags, ',') AS t(tag)
ON CONFLICT (name) DO NOTHING;
INSERT INTO post_tags (post_id, tag_id)
SELECT DISTINCT p.id, g.id
FROM posts p
CROSS JOIN LATERAL string_to_table(p.tags, ',') AS t(tag)
JOIN tags g ON g.name = trim(t.tag);

Quick reference

  • Nouns become tables, describing facts become columns, verbs become relationships
  • One-to-many: the foreign key goes on the many side, and you add an index on it
  • Many-to-many: a join table with both FKs and a composite PRIMARY KEY
  • One-to-one: FK plus UNIQUE, or share the parent's primary key
  • Facts about a pair (grade, quantity) belong on the join table
  • Crow's foot: bar = one, crow's foot = many, circle = optional
  • Self reference: employees.manager_id REFERENCES employees(id)

Common mistakes

  • Storing a comma-separated list of ids in one column instead of a join table.
  • Columns like author1, author2, author3.
  • Mixing two different entities in one table.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Each order has exactly one customer, and a customer can have many orders. Where does the foreign key go?

Question 2

2Students take many courses and courses have many students. Where should a student's grade for a course be stored?

Question 3

3How do you make a foreign key relationship one-to-one?

Question 4

4In crow's foot notation, what does a small circle next to a crow's foot mean?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    A blog has authors and posts. Each post has one author; authors write many posts. Write the two CREATE TABLE statements and the index you need.

  2. Exercise 2medium

    Model employees where each employee may have one manager, who is also an employee. Then list each employee with their manager's name, including the CEO who has none.

  3. Exercise 3hard

    Design tables for a cinema: films, screens, showings (a film on a screen at a time), customers and tickets (one seat per ticket). No seat may be sold twice for the same showing.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

What is the difference between a logical and a physical data model?
A logical model shows entities, attributes and relationships without database details. A physical model adds real table names, data types, indexes and constraints for one specific database like PostgreSQL.
Should every table have an id column?
Every table needs a primary key. Most entity tables use a generated id, but a pure join table often uses the pair of foreign keys as its primary key instead.
What tool should I use to draw ER diagrams?
Any tool works. dbdiagram.io and Mermaid are text based and easy to keep in Git; pgAdmin and DBeaver can draw a diagram straight from an existing database.
ShareXLinkedInWhatsApp