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?
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
- 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.
- Give every table a primary key. A surrogate
idis fine, but add a unique constraint on the natural key too (an email, an SKU). - Declare every relationship. A column named
customer_idis only a hint.REFERENCES customers (id)is a rule. Choose what happens on delete:RESTRICTfor orders,CASCADEfor items that cannot exist alone. - Make "required" mean required. Put
NOT NULLon every column that must have a value. Nullable should be a decision, not a default. - 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.
- Use the right type. Money as
numeric(12,2)or integer cents, timestamps astimestamptz, 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 NULLor a foreign key to a table that already holds bad rows fails, and cleaning the data is the real work. - Nullable by default. A
NULLin a required column makes everyWHEREand join behave in surprising ways. - Wrong delete rule.
CASCADEon 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?
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?
Practice items, not counted towards your mastery.
Start here
- PostgreSQL: Data definition (opens in a new tab)DocsFree
How tables, constraints, row security and schema changes are declared in PostgreSQL.
- PostgreSQL: Constraints (opens in a new tab)DocsFree
Exact behaviour of CHECK, NOT NULL, UNIQUE, primary and foreign keys and their ON DELETE actions.
- PostgreSQL: ALTER TABLE (opens in a new tab)DocsFree
Which ALTER TABLE forms rewrite the table or take strong locks, and the NOT VALID option.