Skip to content

Lesson 11 of 29Designing schemas

Modelling Data: Entities and Relationships

Turn a feature brief into tables: entities, cardinality, junction tables, keys, naming, history and the anti-patterns that haunt schemas for years.

13 min read0/4 questions

Until now you have queried a schema someone else designed. This unit is about designing one yourself. Code is cheap to change. A schema with a year of production data in it is not. If you store a discount as a column on orders and the business later allows two codes per order, you are writing a migration, a backfill and a fix for every report that read that column. Data modelling is the skill of asking the right questions before the first CREATE TABLE, so the schema matches how the business actually works. It is also a standard interview exercise: "design the tables for X" is asked at every level, and the answers that stand out are the ones that ask about cardinality and history first.

From a feature brief to entities

Here is a brief you might get on a Monday: "Customers place orders for products. We want discount codes, and customers must be able to return some or all of the items in an order for a refund."

A reliable first pass is a grammar exercise:

  • Nouns that the business tracks over time become entities, and each entity becomes a table: customer, order, product, discount code, return.
  • Verbs between nouns become relationships: a customer places orders, an order contains products, an order uses discount codes, a return refunds items.
  • Adjectives and facts become attributes, which are columns: a product's price, a code's percentage, a return's reason.

Then comes the part juniors skip: cardinality. For every relationship, ask two questions, one from each side. "Can one order use more than one discount code?" "Can one code be used on more than one order?" "Can one return cover items from two different orders?" "Can a customer return half of the three keyboards they bought?" The answers decide the shape of the tables, and the product manager often has not thought about them. Asking is not slowing down. It is the job.

For this brief, say the answers are: an order can stack several codes, a code is used on many orders, a return belongs to exactly one order, and a return can take back part of a line's quantity.

Three kinds of relationship

One-to-many is the most common. One customer has many orders, and each order has one customer. You model it with a foreign key on the "many" side: orders.customer_id REFERENCES customers(id). Never the other way round. A customers.order_ids column cannot hold many values properly.

Many-to-many needs a third table, called a junction table (also a join, link or associative table). Orders and products are many-to-many: an order has many products, and a product appears on many orders. The course dataset's order_items is that junction table, with a composite primary key (order_id, product_id).

The important insight is that a junction table is often a real entity with its own attributes. order_items is not just two ids. It holds quantity and unit_price_cents, facts that belong to neither the order nor the product alone, but to "this product on this order". When you find yourself wanting to store a fact about a pair, that is the junction table telling you it exists.

One-to-one is rarer: one row on each side at most. You model it with a foreign key that is also UNIQUE (or is the primary key). Reasons to split one entity into two tables include rarely used wide columns (a user's long profile text), data with different access rules (payment details in a locked-down table), or an optional extension (only some customers have a business_accounts row). If neither reason applies, a one-to-one is usually just extra columns on the same table.

Here is the brief as tables. The discount relationship is many-to-many, so it gets a junction table with the amount actually taken off. A return is one-to-many from orders, and return_items points at the order line with a composite foreign key, so you cannot return a product that was never on that order.

Python
from shopdb import connect, showdb = connect()db.executescript("""CREATE TABLE discount_codes ( id INTEGER PRIMARY KEY, code TEXT NOT NULL UNIQUE, percent_off INTEGER NOT NULL CHECK (percent_off BETWEEN 1 AND 100), expires_at TEXT);CREATE TABLE order_discounts ( order_id INTEGER NOT NULL REFERENCES orders(id), discount_code_id INTEGER NOT NULL REFERENCES discount_codes(id), amount_off_cents INTEGER NOT NULL, PRIMARY KEY (order_id, discount_code_id));CREATE TABLE returns ( id INTEGER PRIMARY KEY, order_id INTEGER NOT NULL REFERENCES orders(id), reason TEXT NOT NULL, created_at TEXT NOT NULL);CREATE TABLE return_items ( return_id INTEGER NOT NULL REFERENCES returns(id), order_id INTEGER NOT NULL, product_id INTEGER NOT NULL, quantity INTEGER NOT NULL CHECK (quantity > 0), PRIMARY KEY (return_id, product_id), FOREIGN KEY (order_id, product_id) REFERENCES order_items (order_id, product_id));INSERT INTO discount_codes VALUES (1, 'SPRING10', 10, '2025-04-30'), (2, 'BOOKS5', 5, NULL);INSERT INTO order_discounts VALUES (2, 2, 420), (3, 1, 2990), (5, 1, 2560);INSERT INTO returns VALUES (1, 5, 'damaged', '2025-04-10');INSERT INTO return_items VALUES (1, 5, 5, 1); -- one of the two mice on order 5""")show(db, """SELECT o.id AS order_id, SUM(oi.quantity * oi.unit_price_cents) AS gross, COALESCE((SELECT SUM(d.amount_off_cents) FROM order_discounts d WHERE d.order_id = o.id), 0) AS discounts, COALESCE((SELECT SUM(ri.quantity * li.unit_price_cents) FROM return_items ri JOIN order_items li ON li.order_id = ri.order_id AND li.product_id = ri.product_id WHERE ri.order_id = o.id), 0) AS refundedFROM orders oJOIN order_items oi ON oi.order_id = o.idWHERE o.id IN (2, 3, 5)GROUP BY o.id""")try: db.execute("INSERT INTO return_items VALUES (1, 5, 1, 1)") # product 1 was never on order 5except Exception as e: print("Rejected:", e)
Output
Press Run (⌘ Enter) to see what happens.

The discount and refund totals use subqueries rather than joins on purpose. Joining two one-to-many tables onto the same order multiplies rows, the fan-out trap from Joins of Every Kind.

Drawing it: crow's-foot notation

Teams sketch schemas as ER (entity-relationship) diagrams, and the notation you will see most is crow's foot. Each end of a line says how many rows can be on that side:

Symbol at the line endMeans
a single bar |exactly one
a circle and bar o|zero or one
a crow's foot <many
a circle and crow's foot o<zero or many

So customers |──o< orders reads "each order has exactly one customer, and a customer has zero or many orders". The circle is the optionality, and it maps to SQL directly: a "must have one" side is a NOT NULL foreign key, a "may have one" side is a nullable one. Tools like dbdiagram.io, Mermaid's erDiagram, or the ER view in DBeaver and DataGrip draw these from your schema. Step through the shop's model.

The shop's entities and relationships
customers: id, emailcustomersid, emailorders: customer_idorderscustomer_idorder_items: qty, unit priceorder_itemsqty, unit priceproducts: price_centsproductsprice_centsorder_discounts: amount_offorder_discountsamount_offdiscount_codes: code, percentdiscount_codescode, percentreturns: order_id, reasonreturnsorder_id, reasonreturn_items: line, qtyreturn_itemsline, qty1 to 0..many1 to 1..many1 to 0..many1 to 0..many1 to 0..many1 to 0..many1 to 1..manyline returned

One-to-many: the foreign key orders.customer_id sits on the many side. It is NOT NULL, because every order has a customer.

1/4

Reading a schema you did not design

On your first week you will inherit a schema, not draw one. In PostgreSQL, \d orders in psql lists columns, indexes, constraints and the foreign keys pointing in and out. For scripts and tooling, the standard information_schema views work across databases:

-- PostgreSQL: every foreign key in the public schema
SELECT tc.table_name, kcu.column_name,
       ccu.table_name AS references_table, ccu.column_name AS references_column
FROM information_schema.table_constraints tc
JOIN information_schema.key_column_usage kcu
  ON kcu.constraint_name = tc.constraint_name AND kcu.table_schema = tc.table_schema
JOIN information_schema.constraint_column_usage ccu
  ON ccu.constraint_name = tc.constraint_name AND ccu.table_schema = tc.table_schema
WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = 'public'
ORDER BY tc.table_name;

SQLite keeps its catalogue in sqlite_schema and exposes foreign keys through a pragma you can query like a table. This is the course dataset's full set of relationships:

Python
from shopdb import connect, showdb = connect()show(db, """SELECT t.name AS table_name, fk."from" AS column_name, fk."table" AS references_table, fk."to" AS references_columnFROM sqlite_schema t, pragma_foreign_key_list(t.name) fkWHERE t.type = 'table'ORDER BY t.name""")
Output
Press Run (⌘ Enter) to see what happens.
Match the pairs0/5 matched

Match each requirement to how you model it.

Choose an item, then its match on the other side.

Keys: natural, surrogate, integer or UUID

A natural key is a real-world value that is already unique: an email, an ISBN, a country code. A surrogate key is an id the database invents and that means nothing. Most teams use surrogate primary keys and put a UNIQUE constraint on the natural key. The reason is that natural keys change more often than anyone expects. People change their email, products get re-coded, and a natural primary key that changes must be updated in every table that references it. Natural keys are fine for stable codes like ISO country or currency codes.

For the surrogate itself you have two common choices:

  • bigint GENERATED ALWAYS AS IDENTITY: 8 bytes, sequential, compact indexes, easy to read in logs. Use bigint, not integer. A busy table reaching 2.1 billion ids has caused real outages, and changing a primary key's type on a big table is painful. serial is the legacy way to do the same thing.
  • UUID: 16 bytes, can be generated by the app or any service without asking the database, and safe to merge across systems. The common UUIDv4 is random, so new rows land on random pages of the primary key index. On large tables that means more page splits, a bloated index and worse cache use. UUIDv7 starts with a timestamp, so new ids are roughly increasing and insert like a sequence. PostgreSQL 18 has a built-in uuidv7() function, and most languages have a library for it.

A separate concern is exposing ids. If your URL is /orders/1043, anyone can try /orders/1044. Authorisation must stop that anyway, but sequential ids also leak business volume (a competitor can place two orders a week apart and subtract). A common pattern is a bigint primary key internally, plus a random public identifier (a UUID or a short random token) with a UNIQUE index for URLs and APIs.

-- PostgreSQL 18
CREATE TABLE orders (
  id          bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  public_id   uuid NOT NULL DEFAULT uuidv7() UNIQUE,
  customer_id bigint NOT NULL REFERENCES customers (id),
  status      text NOT NULL,
  created_at  timestamptz NOT NULL DEFAULT now()
);

One caveat with UUIDv7 as a public id: its first bits are a timestamp, so it reveals when the row was created. Usually that is harmless. If creation time is sensitive, use a random v4 for the public id.

Quick check
A table with 500 million rows uses random UUIDv4 primary keys. Insert latency keeps creeping up and the primary key index is much larger than expected. What is the most likely cause?
Need a nudge? A hint rules out a wrong answer.

Naming conventions

Naming is not cosmetic. Every query, ORM model and analyst's dashboard repeats these names for years. Pick conventions and write them down:

  • snake_case for everything. In Postgres, unquoted names are folded to lower case, so CustomerId becomes customerid, and quoting "CustomerId" means you must quote it forever.
  • Plural or singular table names: either is fine, mixing is not. This course uses plural (orders).
  • Foreign keys named <entity>_id: customer_id, manager_id. A reader should know what a column points at without opening the schema.
  • Timestamps as created_at and updated_at, stored as timestamptz. Booleans read as questions: is_active, has_shipped.
  • Units in the name when a number has one: price_cents, timeout_ms, weight_grams.
  • Avoid reserved words such as user, order and group as table names. They work only when quoted.

Modelling history

The most expensive modelling mistake is storing only the current state when the business needs the past.

Snapshot what was true at the time. order_items.unit_price_cents copies the product's price when the order was placed. That looks like duplication, but it is a different fact: "the price on 1 February" versus "the price today". If you computed order totals from products.price_cents, every price change would silently rewrite last year's revenue.

Python
from shopdb import connect, showdb = connect()db.execute("UPDATE products SET price_cents = 249900 WHERE id = 1") # Laptop Pro price riseshow(db, """SELECT oi.order_id, oi.quantity * oi.unit_price_cents AS paid_cents, oi.quantity * p.price_cents AS at_todays_priceFROM order_items oiJOIN products p ON p.id = oi.product_idWHERE oi.product_id = 1""")
Output
Press Run (⌘ Enter) to see what happens.

The same goes for shipping addresses, tax rates and exchange rates: copy them onto the order.

Predict the outputSQL

What does this print?

-- order_items row: (order 1, product 1, quantity 1, unit_price_cents 189900)
UPDATE products SET price_cents = 249900 WHERE id = 1;

SELECT SUM(quantity * unit_price_cents)
FROM order_items WHERE order_id = 1 AND product_id = 1;
Need a nudge? Hints walk you through it.

Keep a status history, not just a status. orders.status tells you where an order is now. It cannot tell you how long orders wait between paid and shipped, or who cancelled one. Add a table order_status_changes (order_id, from_status, to_status, changed_by, changed_at) and write a row on every transition, in the same transaction as the update. Keeping orders.status as well is fine and fast to query. The history table is the audit trail.

Append-only event tables like the dataset's events go further: rows are only ever inserted, never updated. They are ideal for analytics and auditing, and they grow fast, so plan for partitioning or archiving early.

Anti-patterns that last for years

Entity-attribute-value (EAV). One table attributes (entity_id, name, value text) to "store anything". It feels flexible. In practice you lose types (every value is text), constraints (nothing stops weight = 'heavy'), and readable queries (a pivot with a join per attribute). If you truly need flexible attributes, a jsonb column with a few CHECK constraints is usually better, as you will see in JSON in Postgres later in the course.

Polymorphic associations. A comments table with commentable_type = 'post' and commentable_id = 42, popular in Rails and Laravel. A foreign key can only reference one table, so the database cannot check that post 42 exists:

Python
import sqlite3from shopdb import connect, showdb = connect()db.executescript("""CREATE TABLE posts (id INTEGER PRIMARY KEY, title TEXT NOT NULL);CREATE TABLE comments_poly ( id INTEGER PRIMARY KEY, commentable_type TEXT NOT NULL, commentable_id INTEGER NOT NULL, body TEXT NOT NULL);CREATE TABLE comments ( id INTEGER PRIMARY KEY, post_id INTEGER REFERENCES posts(id), product_id INTEGER REFERENCES products(id), body TEXT NOT NULL, CHECK ((post_id IS NOT NULL) + (product_id IS NOT NULL) = 1));INSERT INTO posts VALUES (1, 'Launch notes');""")db.execute("INSERT INTO comments_poly VALUES (1, 'post', 999, 'points at nothing')")print("Polymorphic insert accepted, post 999 does not exist")attempts = [ ("post 999 that does not exist", (1, 999, None)), ("both a post and a product", (2, 1, 3)), ("post 1 only", (3, 1, None)),]for label, (cid, post_id, product_id) in attempts: try: db.execute("INSERT INTO comments VALUES (?, ?, ?, 'hi')", (cid, post_id, product_id)) print(f"accepted: {label}") except sqlite3.IntegrityError as e: print(f"rejected: {label} ({e})")
Output
Press Run (⌘ Enter) to see what happens.

The fix shown is an exclusive arc: one nullable foreign key per target table and a CHECK that exactly one is set. In Postgres you can write that check as CHECK (num_nonnulls(post_id, product_id) = 1). With many target types, a separate junction table per target (post_comments, product_comments) is another option.

Lists in a column. tags = 'sql,postgres,perf'. You cannot index one tag, join on it, or stop a typo, and "remove one tag" becomes string surgery. Use a junction table. Postgres arrays are a reasonable middle ground for small, simple lists you never join on.

The god table. One users table with 140 columns because every feature added "just one more". Most rows have most columns NULL, every migration touches the hottest table, and nobody knows which columns are still used. Split by concept (profiles, preferences, billing) when a group of columns belongs to a different lifecycle or owner.

Multi-tenant basics

B2B SaaS products serve many customer companies (tenants) from one system, and the model must keep their data apart. There are three common shapes:

ApproachHowGoodHard
Shared tablesa tenant_id column on every tableone schema, cheap, simple migrationsevery query must filter; one bug leaks data
Schema per tenantone Postgres schema eachstronger separation, easy per-tenant exportmigrations run N times; thousands of schemas strain tooling
Database per tenantone database eachstrongest isolation, per-tenant restoremost expensive, most operational work

Most startups begin with shared tables. Include tenant_id in composite keys and indexes ((tenant_id, id)), so queries stay fast and foreign keys cannot point across tenants. Postgres row-level security can enforce the tenant filter inside the database as a safety net. Check the Postgres docs on CREATE POLICY before relying on it.

Put it in order5 steps

Put these modelling steps in a sensible order for a new feature.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
entity
A thing the business tracks over time, such as a customer or an order. Each entity usually becomes a table.
cardinality
How many rows on one side of a relationship can relate to a row on the other side: one-to-one, one-to-many or many-to-many.
junction table
A table that resolves a many-to-many relationship with a foreign key to each side, often holding facts about the pair.
surrogate key
A meaningless id generated by the database or app, used as the primary key instead of a real-world value.
UUIDv7
A UUID that starts with a timestamp, so new ids are roughly ordered and insert into a B-tree like a sequence. Built into PostgreSQL 18 as uuidv7().
polymorphic association
One id column that can point at different tables depending on a type column. No foreign key can enforce it.
EAV
Entity-attribute-value: storing attributes as rows of name and value text. Flexible, but loses types, constraints and readable queries.