Relational Modeling & Normalization
- Turn a business description (orders, payments, accounts) into an ER model with correct cardinalities and keys
- Choose between natural and surrogate keys and explain why you usually want both
- Normalize a flat e-commerce table step by step to 3NF/BCNF and name the anomaly each step removes
- Decide when to denormalize for reads, and how to keep the copy correct
- Encode invariants as
CHECK,UNIQUE, foreign key and exclusion constraints instead of hoping the application gets them right
TL;DR
- Model the business facts first (entities, relationships, cardinalities), then the tables. Each fact should live in exactly one place unless you have a reason and a sync mechanism.
- Use a surrogate primary key (
bigintidentity or UUIDv7) for joins, plus aUNIQUEconstraint on the natural key (SKU code, IBAN, ISO currency) so duplicates are impossible. - Normal forms remove update anomalies: 1NF (atomic values), 2NF (no partial dependency on a composite key), 3NF (no transitive dependency), BCNF (every determinant is a key).
- A snapshot is not denormalization:
order_line.unit_priceis the price at purchase time, a different fact fromproduct.current_price. - Denormalize for read paths (counters, balances, read models) only with a defined owner and an update path: same transaction, trigger, or async via outbox/CDC plus reconciliation.
- Constraints are the last line of defense for money and inventory invariants. They run on every write path, including the one a future teammate adds with a script at 2 a.m.
Why it matters
In banking and e-commerce, a modeling mistake is not a style issue but a correctness incident. If a customer's email lives in both customers and orders, a profile update leaves old orders pointing to a stale address, and a GDPR erasure request misses copies. If an account's balance is stored in two places without a defined owner, reconciliation finds a mismatch and someone spends a week explaining it to auditors. If nothing prevents two "default" shipping addresses or two overlapping price periods for the same SKU, the application eventually creates them, because concurrency and retries find every gap.
Interviewers for architect roles probe this because the data model outlives every service built on top of it. Code can be rewritten in a sprint; a production schema with five years of ledger history is migrated slowly and carefully (see Zero-Downtime Schema Migrations).
Core concepts
ER modeling: entities, relationships, cardinality
Start from nouns and verbs in the domain: a customer places orders, an order contains lines, each line refers to a SKU, a payment settles an order. For every relationship, ask two cardinality questions in both directions: "can it be zero?" and "can it be many?".
Things worth noticing in this model:
ORDER_LINEis a weak entity: it has no meaning without its order, so its key is(order_id, line_no).ORDERS ||--o{ PAYMENT: an order can have zero payments (unpaid), or several (a failed attempt then a success, or split tender).SKU_PRICEis a time-varying relationship. Modeling it as a separate table with a validity range, not apricecolumn onSKU, is what lets you answer "what was the price on Black Friday?".- Many-to-many relationships (product ↔ category) become a junction table with a composite key
(product_id, category_id).
Keys: candidate, primary, natural, surrogate
A candidate key is a minimal set of columns that uniquely identifies a row. You choose one as the primary key; the others become alternate keys, enforced with UNIQUE.
| Key style | Example | Strengths | Weaknesses |
|---|---|---|---|
| Natural key | currency.code = 'VND', country.iso2 | Meaningful, no lookup needed, stable for standards-based codes | Real-world identifiers change (emails, phone numbers, even SKU codes after a rebrand); often wide strings |
| Surrogate key | bigint generated always as identity, UUIDv7 | Stable forever, compact, cheap joins | No business meaning; without a UNIQUE on the natural key you will get duplicates |
| Composite key | order_line (order_id, line_no) | Expresses ownership; keeps child rows clustered by parent (InnoDB) | Every referencing table must carry all columns |
The pragmatic rule: surrogate PK + UNIQUE on the natural key. A customer's id never changes, while email is unique (case-insensitively, via a unique index on lower(email)) but can be updated. Standards-based codes such as ISO 4217 currency codes are stable enough to be the primary key of a lookup table.
In MySQL/InnoDB the primary key is the clustered index: rows are physically ordered by it and every secondary index stores the PK value. A wide or random PK makes every index bigger and inserts scattered. Postgres stores rows in an unordered heap, so the PK choice matters less for layout but still matters for index size. See Indexing and the UUID discussion in Schema Patterns.
Functional dependencies: the idea behind normal forms
A functional dependency X → Y means "if two rows agree on X, they must agree on Y". sku_id → product_name says a SKU has exactly one product name. Normalization is the process of making sure every dependency is enforced by a key, so a fact is stored once and cannot disagree with itself.
Normalizing a flat order table
Imagine an export from a legacy system, stored as one table:
| order_id | order_date | customer_id | customer_email | ship_city | ship_zip | items |
|---|---|---|---|---|---|---|
| 1001 | 2025-11-28 | 7 | an@example.com | Hanoi | 100000 | SKU-1 x2 @150000; SKU-9 x1 @90000 |
1NF — atomic values, no repeating groups. The items column packs several facts into one string; you cannot index, constrain or join on it. Columns like phone1, phone2, phone3 are the same problem in disguise. Split lines into rows:
order_items(order_id, line_no, sku_id, sku_name, quantity, unit_price, order_date, customer_id, customer_email, ship_city, ship_zip) with key (order_id, line_no).
2NF — no partial dependency on part of a composite key. order_date, customer_id, customer_email, ship_* depend on order_id alone, not on the whole key (order_id, line_no). sku_name depends only on sku_id. Anomaly: changing an order's shipping city means updating every line, and a half-applied update leaves the order with two cities. Move order-level columns to orders(order_id, …) and SKU-level columns to sku(sku_id, sku_name, …).
3NF — no transitive dependency through a non-key column. In orders(order_id, customer_id, customer_email, ship_zip, ship_city), customer_email depends on customer_id, not on the order. Anomaly: the customer changes their email and you must rewrite their entire order history (or leave it inconsistent). Move email to customers. Similarly, if zip → city truly holds in your country, ship_city is transitively dependent; in practice many teams accept this one because postal data is messy and shipping addresses are snapshots anyway (see below).
BCNF — every determinant is a candidate key. 3NF still allows a dependency X → A when A is part of some candidate key. A concrete e-commerce case: the vendor-management table product_supplier(product_id, supplier_id, account_manager) with the business rules:
- For each product–supplier pair there is exactly one account manager:
(product_id, supplier_id) → account_manager. - Each account manager works for exactly one supplier:
account_manager → supplier_id.
Candidate keys are (product_id, supplier_id) and (product_id, account_manager). Every attribute is part of some candidate key, so the table is in 3NF, but account_manager → supplier_id has a determinant that is not a key, so it is not BCNF. Anomaly: a manager moving to another supplier requires updating many rows. The BCNF decomposition is manager(account_manager PK, supplier_id) plus product_manager(product_id, account_manager). The catch, which interviewers like: rule 1 is no longer enforceable with a single UNIQUE constraint, because supplier_id and product_id now live in different tables. BCNF can cost you dependency preservation; sometimes 3NF plus a constraint is the better engineering choice.
4NF and 5NF deal with independent multi-valued facts (a product's colors and its sizes stored as a cross product) and join dependencies. You rarely need the terminology, but recognize the smell: a table whose row count is the product of two unrelated lists.
Snapshots are facts, not duplication
order_line.unit_price_minor and the shipping address on an order look like denormalized copies of sku_price and address. They are not: they record what was agreed at checkout. If the merchant changes the price tomorrow, yesterday's invoice must not change. The same holds for the exchange rate used on a cross-currency payment and the fee schedule applied to a transfer. Ask "is this the current value or the value at the time of the event?" Event-time values belong to the event row and are immutable.
Denormalization for reads
Normalized schemas optimize writes and integrity; read paths sometimes need precomputed shapes. Common deliberate denormalizations:
| Denormalization | Example | How to keep it correct |
|---|---|---|
| Stored aggregate | accounts.balance_minor derived from ledger_entries | Update in the same transaction as the entry insert; nightly reconciliation compares it with SUM(amount) |
| Counter | products.review_count | Same transaction, or async with eventual consistency (acceptable for display) |
| Copied attribute | orders.customer_tier for fast filtering | Decide whether it is a snapshot (never updated) or a cache (updated by an event) |
| Materialized view | Daily merchant sales | REFRESH MATERIALIZED VIEW CONCURRENTLY (needs a unique index) on a schedule |
| Read model / search index | Catalog in Elasticsearch | Outbox or CDC stream, see Transactional Outbox & CDC |
The architect's question is always "who owns the truth, and what happens when the copy is wrong?" A display counter that lags by a minute is fine. An available balance that lags lets customers overspend. For larger read/write separation, see CQRS & Event Sourcing.
Constraints as invariants
Write down the invariants, then encode each one at the lowest layer that can enforce it.
| Invariant | Constraint |
|---|---|
| Amount on a payment is positive | CHECK (amount_minor > 0) |
| Currency is an ISO code we support | FOREIGN KEY (currency) REFERENCES currency(code) |
| Order status is one of a known set | CHECK (status IN ('PENDING','PAID','SHIPPED','CANCELLED')) or a lookup table |
| One account per customer per currency | UNIQUE (customer_id, currency) |
| At most one default address per customer | Partial unique index ON address (customer_id) WHERE is_default |
| Price periods for a SKU never overlap | Exclusion constraint with tstzrange and && |
| Lines cannot exist without their order | FOREIGN KEY … ON DELETE CASCADE (only for owned children) |
| A paid order cannot be deleted | ON DELETE RESTRICT plus no DELETE grant |
Postgres-specific tools worth knowing:
- Exclusion constraints generalize
UNIQUE: "no two rows where these operators all return true". With thebtree_gistextension you can combine equality on a scalar with overlap on a range. This is the clean way to prevent double-booking a hotel room or overlapping price validity. - Deferrable constraints (
DEFERRABLE INITIALLY DEFERRED) are checked at commit instead of per statement, useful for circular references or swapping unique values. NOT VALID+VALIDATE CONSTRAINTlets you add a constraint to a large table without a long lock (see Zero-Downtime Schema Migrations).
MySQL differences: CHECK constraints are only enforced from 8.0.16 (earlier versions parsed and ignored them); there are no exclusion constraints and no partial indexes (emulate with a generated column that is NULL when the condition is false, then index it, since unique indexes allow many NULLs); InnoDB automatically creates an index for a foreign key if none exists, while Postgres does not.
Some invariants span rows and cannot be a simple constraint: "the entries of a journal sum to zero" in a double-entry ledger, or "an account's balance never goes below its overdraft limit". Enforce those with a single conditional UPDATE, a constraint trigger, or serializable transactions, covered in Transactions & Isolation Levels and Locking & Concurrency Control.
Trade-offs
| Option | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| Fully normalized (3NF/BCNF) | One place per fact, easy updates, constraints express invariants | More joins on read paths; aggregates computed on demand | OLTP core: ledgers, orders, customer master data |
| Snapshot columns on events | Historical correctness, immutable records, simple reads | Storage cost; must be clear which values are snapshots | Prices, addresses, FX rates, fees at transaction time |
| Denormalized aggregate (same transaction) | Fast reads, always consistent | Hot rows and lock contention on popular aggregates | Account balances, stock counters with moderate write rates |
| Denormalized copy (async) | Write path stays fast, read model shaped for queries | Staleness, needs reconciliation and replay | Search, dashboards, feeds, reporting |
| JSONB attributes | Flexible per-category attributes, no migration per field | Weak constraints, harder to query and validate | Product specs that vary by category, external payloads |
In practice
A compact Postgres schema for the order model above, with invariants in the DDL:
CREATE EXTENSION IF NOT EXISTS btree_gist;
CREATE TABLE currency (
code char(3) PRIMARY KEY CHECK (code ~ '^[A-Z]{3}$'),
minor_units smallint NOT NULL CHECK (minor_units BETWEEN 0 AND 4)
);
CREATE TABLE customer (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX customer_email_uq ON customer (lower(email));
CREATE TABLE address (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id bigint NOT NULL REFERENCES customer (id),
line1 text NOT NULL,
city text NOT NULL,
is_default boolean NOT NULL DEFAULT false
);
CREATE INDEX address_customer_idx ON address (customer_id);
CREATE UNIQUE INDEX address_one_default_uq ON address (customer_id) WHERE is_default;
CREATE TABLE sku (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
sku_code text NOT NULL UNIQUE,
name text NOT NULL
);
CREATE TABLE sku_price (
sku_id bigint NOT NULL REFERENCES sku (id),
currency char(3) NOT NULL REFERENCES currency (code),
price_minor bigint NOT NULL CHECK (price_minor >= 0),
valid_during tstzrange NOT NULL,
EXCLUDE USING gist (sku_id WITH =, currency WITH =, valid_during WITH &&)
);
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id bigint NOT NULL REFERENCES customer (id),
status text NOT NULL DEFAULT 'PENDING'
CHECK (status IN ('PENDING', 'PAID', 'SHIPPED', 'CANCELLED')),
currency char(3) NOT NULL REFERENCES currency (code),
total_minor bigint NOT NULL CHECK (total_minor >= 0),
ship_line1 text NOT NULL, -- snapshot, not a reference
ship_city text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX orders_customer_idx ON orders (customer_id, created_at DESC);
CREATE TABLE order_line (
order_id bigint NOT NULL REFERENCES orders (id) ON DELETE CASCADE,
line_no int NOT NULL CHECK (line_no > 0),
sku_id bigint NOT NULL REFERENCES sku (id),
quantity int NOT NULL CHECK (quantity > 0),
unit_price_minor bigint NOT NULL CHECK (unit_price_minor >= 0), -- snapshot
PRIMARY KEY (order_id, line_no)
);
CREATE INDEX order_line_sku_idx ON order_line (sku_id);
Note the explicit indexes on the foreign key columns that point at parents which are deleted or have their keys changed (address.customer_id, order_line.sku_id; order_line.order_id is covered by the primary key). Postgres does not create them, and without them a DELETE on the parent scans the child table and holds locks longer. References to small, static lookup tables such as currency can usually skip the index, since those parent rows are never deleted.
Constraint violations are part of your API contract. Map SQLSTATE codes to domain errors instead of returning a generic 500:
package store
import (
"errors"
"github.com/jackc/pgx/v5/pgconn"
)
var (
ErrDuplicate = errors.New("duplicate")
ErrInvalidRef = errors.New("referenced entity does not exist")
ErrRuleViolation = errors.New("business rule violated")
ErrPeriodOverlaps = errors.New("validity period overlaps an existing one")
)
// MapPgError converts constraint violations into domain errors.
func MapPgError(err error) error {
var pgErr *pgconn.PgError
if !errors.As(err, &pgErr) {
return err
}
switch pgErr.Code {
case "23505": // unique_violation
return ErrDuplicate
case "23503": // foreign_key_violation
return ErrInvalidRef
case "23514": // check_violation
return ErrRuleViolation
case "23P01": // exclusion_violation
return ErrPeriodOverlaps
default:
return err
}
}
pgErr.ConstraintName tells you which constraint fired, so you can return "email already registered" versus "SKU code taken" without parsing messages. Name constraints deliberately for this reason.
Common pitfalls
- Foreign keys without indexes on the referencing column (Postgres). Symptom: deleting or updating a parent row is slow and blocks concurrent writers;
pg_stat_user_tables.seq_scanclimbs on the child table. - Natural key as primary key when it can change. Using email or phone as PK; a customer changes it and you cascade updates across ten tables, or worse, cannot.
- Treating snapshots as references. An invoice joins to
product.priceinstead of storing the line price; reprinting an old invoice shows today's price. Auditors notice. - Stored aggregates with no reconciliation.
balancedrifts fromSUM(ledger)after a bug or a manual fix, and nobody finds out until a customer complains. ON DELETE CASCADEon financial data. Deleting a customer silently removes payment history. UseRESTRICTand an explicit closure/anonymization process.- Constraints only in application code. The batch job, the admin tool, or the second service bypasses them. Symptom: "impossible" rows in production.
- Entity-Attribute-Value tables (
entity_id, attr_name, attr_value text) to avoid migrations. You lose types, constraints and sane queries; JSONB with validation is usually better. - Nullable booleans and magic values.
is_active NULLmeans a third state nobody documented;-1means "unknown amount".
Interview angle
- Expect "design the schema for X" early in a system design round (orders, wallets, bookings). A strong answer lists entities, keys, cardinalities, invariants and which constraint enforces each, and the two or three hot queries with their indexes.
- Be ready to normalize on the whiteboard and to name the anomaly each normal form removes. Bonus points for the BCNF dependency-preservation trade-off.
- Explain snapshot versus reference for prices and addresses; it signals you have built real commerce systems.
- When you denormalize, say who owns the truth, how the copy is updated, and how drift is detected.
- Follow-ups: "How do you prevent double booking?" (exclusion constraint or unique slot rows), "How do you add a constraint to a 2-billion-row table?" (
NOT VALIDthenVALIDATE), "Natural or surrogate key for accounts?" (surrogate PK plus unique account number). - Red flags: "we validate in the service so the DB doesn't need constraints", storing money as float, "NoSQL so we don't need a schema".
Self-check
1. What is the difference between a candidate key, a primary key and an alternate key?
A candidate key is any minimal column set that uniquely identifies rows. The primary key is the one candidate key you choose as the row's identity (and, in InnoDB, as the clustering key). Every other candidate key is an alternate key and should still be enforced with a UNIQUE constraint, otherwise the database will accept duplicates of the business identifier.
2. Why is order_line.unit_price not a violation of 3NF?
Because it is a different fact. sku_price holds the current or scheduled price; order_line.unit_price holds the price agreed at checkout, which depends on the order line itself, not transitively on the SKU. It must never change when the catalog price changes. Normal forms are about functional dependencies, and the event-time price is determined by the line, not by sku_id.
3. Give an example of a table that is in 3NF but not in BCNF, and the cost of decomposing it.
product_supplier(product_id, supplier_id, account_manager) where each manager belongs to one supplier. account_manager → supplier_id has a non-key determinant, so it is not BCNF, yet every attribute is prime, so it is 3NF. Decomposing into manager(account_manager, supplier_id) and product_manager(product_id, account_manager) removes redundancy but loses the ability to enforce "one manager per product–supplier pair" with a single UNIQUE constraint.
4. How do you guarantee that a customer has at most one default address in Postgres and in MySQL?
Postgres: a partial unique index CREATE UNIQUE INDEX … ON address (customer_id) WHERE is_default. MySQL has no partial indexes, so add a generated column such as default_owner = IF(is_default, customer_id, NULL) and put a unique index on it; multiple NULLs are allowed, so only rows with is_default = true compete.
5. Scenario: a hotel booking system must never assign overlapping stays to the same room. What do you do?
Store each booking with room_id and a daterange stay, and add EXCLUDE USING gist (room_id WITH =, stay WITH &&) (requires btree_gist). Concurrent inserts that overlap fail with SQLSTATE 23P01, which the application maps to "room no longer available". The alternative without exclusion constraints is one row per room-night with a unique key, which is also what you would do in MySQL.
6. You keep accounts.balance as a denormalized sum of ledger entries. What must be true to make that safe?
The balance update and the entry insert happen in the same transaction, the update is atomic (balance = balance + $1, not read-modify-write in the app), every write path goes through that code or a trigger, and a reconciliation job regularly compares the stored balance with SUM(amount) and alerts on drift. You also need a plan for the hot-row problem on very busy accounts.
7. When is ON DELETE CASCADE appropriate?
Only for children whose lifecycle is fully owned by the parent and that have no independent business or audit meaning, such as order_line for a draft cart or session_attribute rows. For financial records, customers or anything subject to retention rules, use RESTRICT and an explicit process (close, anonymize, archive) instead.
Exercise
Run Postgres locally and make the schema reject bad data.
docker run --name pg-model -e POSTGRES_PASSWORD=pg -p 5432:5432 -d postgres:17
docker exec -it pg-model psql -U postgres
- Paste the DDL from In practice, then insert a currency, a customer, a SKU and two non-overlapping price periods:
INSERT INTO currency VALUES ('VND', 0), ('USD', 2);
INSERT INTO customer (email) VALUES ('an@example.com');
INSERT INTO sku (sku_code, name) VALUES ('SKU-1', 'Coffee beans 1kg');
INSERT INTO sku_price VALUES
(1, 'VND', 150000, tstzrange('2025-11-01', '2025-11-28')),
(1, 'VND', 120000, tstzrange('2025-11-28', '2025-12-01'));
- Try each violation and record the SQLSTATE: an overlapping price period,
AN@example.comas a second customer, two default addresses for one customer, an order withtotal_minor = -1, a currency'usd'. - Take the flat legacy table from the normalization section, create it with three sample orders, and write
INSERT … SELECTstatements that migrate it into the normalized schema. - Write down three invariants of a wallet (for example "balance never below zero", "a transfer debits and credits the same amount") and state which can be a constraint and which needs transactional logic.
Done when every violation in step 2 fails with the expected code, your migration in step 3 produces the same totals as the flat table, and you can justify each answer in step 4.
Further reading
- Martin Kleppmann, Designing Data-Intensive Applications, ch. 2 (data models) — relational vs document trade-offs.
- C. J. Date, Database Design and Relational Theory — rigorous treatment of normal forms and dependencies.
- Michael J. Hernandez, Database Design for Mere Mortals — practical ER modeling.
- PostgreSQL documentation, "Constraints" chapter: postgresql.org/docs/current/ddl-constraints.html.
- MySQL Reference Manual, "CHECK Constraints" and "Generated Columns".
Related
- Indexing — how keys and constraints become indexes, and what that costs.
- Schema Patterns: Money, Audit, Multi-tenancy — money types, history tables, UUID vs bigint.
- Transactions & Isolation Levels — invariants that span rows.
- Double-Entry Ledger Design — the most important schema in a bank.
- Order Management & State Machines — modeling order status and transitions.
- Domain-Driven Design — aggregates and consistency boundaries map onto tables and transactions.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).