Skip to content
mentoor

Topic 1 of 5 · 5 min read

Designing tables from a domain

Goal: Turn a short feature description into tables with keys and constraints that reject the three most likely bad rows.

Design tables so the database itself refuses the rows your application should never create. Application code gets rewritten, bypassed by scripts and edited by agents. Constraints stay.

Check yourself · 1 of 3

What turns a column named customer_id into an enforced relationship?

Choose one answer

Why it matters

Every bad row that reaches a table becomes a bug somewhere else: an order with no customer, two accounts with one email, a negative quantity. Finding the cause weeks later costs far more than a rejected insert today. AI assistants will happily generate a table with nothing but column names and types, because that satisfies the prompt.

How to do it

  1. List the nouns and the verbs. "Customers place orders; an order has several items; each item is one product." Nouns become tables. "Has several" tells you which side holds the foreign key: the many side.
  2. Give every table a primary key. A surrogate id is fine, but add a unique constraint on the natural key too (an email, an SKU).
  3. Declare every relationship. A column named customer_id is only a hint. REFERENCES customers (id) is a rule. Choose what happens on delete: RESTRICT for orders, CASCADE for items that cannot exist alone.
  4. Make "required" mean required. Put NOT NULL on every column that must have a value. Nullable should be a decision, not a default.
  5. Write the CHECK for each rule you can state in a sentence. Quantity above zero, status in a known list, end date not before start date.
  6. Use the right type. Money as numeric(12,2) or integer cents, timestamps as timestamptz, status as an enum or a checked text.

Before and after

-- Weak: accepts almost anything
CREATE TABLE order_items (
  id serial,
  order_id int,
  product text,
  qty int,
  price float
);

-- Strong: bad rows are impossible
CREATE TABLE order_items (
  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  order_id bigint NOT NULL REFERENCES orders (id) ON DELETE CASCADE,
  product_id bigint NOT NULL REFERENCES products (id),
  qty integer NOT NULL CHECK (qty > 0),
  unit_price numeric(12,2) NOT NULL CHECK (unit_price >= 0),
  UNIQUE (order_id, product_id)
);

The strong version rejects an orphan item, a zero quantity and the same product listed twice in one order.

What goes wrong

  • Trusting the app to validate. A data import, a second service or a one-off script skips your validation and the table fills with junk.
  • Constraints added late. Adding NOT NULL or a foreign key to a table that already holds bad rows fails, and cleaning the data is the real work.
  • Nullable by default. A NULL in a required column makes every WHERE and join behave in surprising ways.
  • Wrong delete rule. CASCADE on a customer-to-orders link deletes financial history when one customer row is removed.

Examples

Three bad rows, three constraints

A booking table needs to reject a booking with no room, two bookings for the same room and start time, and an end time before the start. The fixes are room_id bigint NOT NULL REFERENCES rooms (id), UNIQUE (room_id, starts_at) and CHECK (ends_at > starts_at).

Reading an AI-generated table

An assistant returns users(id, email, role) with no constraints. Ask: is email unique, is role limited to known values, can either be null? The fixed table has email text NOT NULL UNIQUE and role text NOT NULL CHECK (role IN ('admin','member')).

Key points

  • A constraint is a rule the database enforces for every writer, including scripts, imports and agents.
  • A column named customer_id is only a hint until REFERENCES makes it a foreign key.
  • Put NOT NULL on every required column and treat nullable as a deliberate choice.
  • Write a CHECK for each business rule you can say in one sentence, such as quantity above zero.
  • Pick the ON DELETE action per relationship: RESTRICT to protect history, CASCADE for rows that cannot stand alone.

Common mistakes

  • Relying on application validation alone and leaving the table unconstrained.
  • Adding a foreign key column without the REFERENCES clause.
  • Choosing CASCADE everywhere, which deletes history when a parent row goes.
  • Storing prices as float and leaving the currency rule unwritten.

Check yourself · 2 of 3

A table allows qty = 0 and qty = -3 for order items. Which constraint fixes this?

Choose one answer

Check yourself · 3 of 3

Customers and their orders: deleting a customer must not erase order history. Which delete rule fits the orders-to-customers foreign key?

Choose one answer

Practice items, not counted towards your mastery.

Start here