Skip to content
Commitwise
Menu
Databases

Schema design and normalization

One fact in one place, the normal forms in plain words, the comma-separated column that matches the wrong rows, when to copy data on purpose (prices, addresses, counters), jsonb vs EAV for flexible attributes, designing a schema in an interview, and changing a live schema with migrations and expand/contract.

intermediate

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

A customer changes their email, and half the old orders still show the old one. Searching lessons tagged “sql” also returns lessons tagged “nosql”. An invoice reprinted a year later shows today’s prices and today’s address. Renaming one column takes the app down for every user still running the old version.

These are schema design problems, and you fix them before writing any query. This lesson covers normalization (where each fact should live), denormalization (when to copy data on purpose), and how to change a schema that’s already in production. It’s also the first half of every “design the database for X” interview question. The examples build on the shop tables from How relational databases work.

New to some of these? Open what you need, or skip ahead.

Basics:Tables, rows and keys

A table has named, typed columns, and each row is one thing (one customer, one order). The primary keyPrimary keyThe column (or columns) that uniquely identifies each row of a table; never empty, never repeated.Open in glossary → (usually id) identifies each row, and a foreign keyForeign keyA column that points at a row in another table, and that the database keeps valid.Open in glossary → like orders.customer_id points at a row in another table.

Basics:JOIN

A join puts rows from two tables side by side, matching them with ON, usually foreign key = primary key: FROM orders o JOIN customers c ON c.id = o.customer_id. An inner join returns one row per match. See Joins.

Part Not started

Normalization: one fact in one place

Imagine the first version of the shop stored everything in one wide table:

order_idcustomer_emailcustomer_nameproduct_namestotal
1001ana@example.comAnaMug, Notebook14.40
1002ana@example.comAnaMug9.90

It looks convenient, until things change:

  • Ana changes her email. It’s stored in every order, so you must update all of them. Miss one, and the data disagrees with itself.
  • “Which orders contain a Mug?” means searching inside the text 'Mug, Notebook'.
  • A new customer who hasn’t ordered yet can’t be stored at all: there’s no order row to put them in.

NormalizationNormalizationDesigning tables so each fact is stored once, in the table it describes.Open in glossary → fixes this with one idea: store each fact once, in the table where it belongs, and point to it by id. The rules have names, the normal forms:

  • First normal form (1NF): one value per cell. No lists like 'Mug, Notebook'. A list becomes rows in another table (order_items).
  • Second (2NF) and third (3NF): every column describes the thing the row is about, and nothing else. customer_email describes a customer, not an order, so it moves to customers, and the order keeps only customer_id.

A memorable summary of 3NF: every column depends on the key, the whole key, and nothing but the key.

After normalizing, we get exactly the shop schema from the first lesson: customers, products, orders and order_items. Ana’s email lives in one row. Changing it changes it everywhere.

  • Functional dependencies are the formal basis: X → Y if a value of X determines Y. 2NF removes partial dependencies on part of a composite key (in order_items(order_id, product_id, product_name), product_name depends only on product_id). 3NF removes transitive dependencies (orders.customer_id → customer_email). BCNF tightens 3NF for tables with overlapping candidate keys; rarely an issue in practice. 4NF/5NF deal with independent multi-valued facts (a person’s skills and languages in one table).
  • Why it matters: update, insert and delete anomalies; constraints can only protect a fact stored once; smaller rows and indexes.
  • 1NF and modern types: PostgreSQL arrays and jsonb technically allow lists in a cell. They’re fine for data you read and write as a whole (a list of image URLs, a settings blob) and wrong for data you filter, join, count or reference with foreign keys (tags you search by, line items).
  • OLTP vs analytics: transactional schemas aim for 3NF; warehouses deliberately denormalize into star schemas (fact tables plus wide dimension tables) because they’re read-mostly and scanned in bulk.
  • Modeling choices interviewers probe: surrogate vs natural keys, nullable column vs separate table (sparse optional data), one-to-one splits (rarely worth it except for very wide or sensitive columns), soft deletes (deleted_at) and their effect on unique constraints (partial unique index WHERE deleted_at IS NULL), and multi-tenancy (tenant_id on every table, in every index and unique key).

Predict the output

Lessons store their tags as text: 'sql,joins' or 'nosql,mongodb'. Which lessons does this return?

SELECT id, title FROM lessons WHERE tags LIKE '%sql%';
-- instead of lessons.tags = 'sql,joins'
CREATE TABLE lesson_tags (
    lesson_id bigint NOT NULL REFERENCES lessons (id) ON DELETE CASCADE,
    tag       text   NOT NULL,
    PRIMARY KEY (lesson_id, tag)
);
CREATE INDEX lesson_tags_tag ON lesson_tags (tag);

-- lessons tagged sql, exactly
SELECT l.id, l.title
FROM lessons l
JOIN lesson_tags t ON t.lesson_id = l.id
WHERE t.tag = 'sql';

-- the most used tags
SELECT tag, count(*) FROM lesson_tags GROUP BY tag ORDER BY count(*) DESC LIMIT 10;

The email that changed only once

Spot the bugOrders that remember the old email

Tap the line with the bug.

CREATE TABLE orders (
    id             bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    customer_id    bigint NOT NULL REFERENCES customers (id),
    customer_email text NOT NULL,
    total          numeric(10, 2) NOT NULL
);

-- "change email" endpoint
UPDATE customers SET email = 'ana.p@example.com' WHERE id = 42;

Deep diveDesigning a schema in an interviewInterview favorite

“Design the database for a ride-sharing app” (or a booking system, a library, a chat). A structure that works:

  1. Clarify the main use cases and their volumes: request a ride, match a driver, track the trip, pay, rate. Which reads are hot (“my trips”, “nearby drivers”), which writes are frequent (locations every 4 seconds)?
  2. Find the entities and their keys: users, drivers (a user with extra data: one-to-one or a role), vehicles, trips, payments, ratings. Surrogate keys; natural identifiers (email, license plate) get UNIQUE.
  3. Relationships and cardinality: a trip has one rider and one driver (FKs on trips); a driver has many vehicles but one active (a partial unique index WHERE active); a trip has many location points (child table, or not in the database at all).
  4. Normalize to 3NF, then name the deliberate copies: the fare and pickup address on the trip (historical facts), the driver’s average rating (a cached aggregate).
  5. State and history: trips.status with allowed values (CHECK or a lookup table) and timestamps per transition, or an append-only trip_events table for auditing.
  6. Indexes from the hot queries: trips (rider_id, created_at DESC), trips (driver_id) WHERE status = 'IN_PROGRESS', a geo index for driver locations (or Redis, since they change every few seconds and don’t need durability).
  7. Constraints that encode rules: one active trip per driver (UNIQUE (driver_id) WHERE status IN (…)), money as numeric/cents, timestamptz.
  8. What doesn’t belong in the OLTP database: high-frequency location pings, analytics, search. Say where they go and why.

Interviewers look for the reasoning (use cases → entities → constraints → indexes), deliberate trade-offs, and rules enforced by the database rather than by hope.

  • Functional dependencies: 2NF (no partial dependencies on a composite key), 3NF (no transitive ones), BCNF rarely matters.
  • Anomalies (update, insert, delete) are the argument; constraints only protect facts stored once.
  • Arrays/jsonb for data used as a whole; child tables for anything filtered, joined, counted or referenced.
  • OLTP in 3NF, analytics in star schemas. Soft deletes need partial unique indexes; multi-tenant keys include tenant_id.

Check this part

  1. What does first normal form forbid?

  2. orders has a customer_email column. What problem does it cause?

  3. order_items(order_id, product_id, product_name, quantity) with key (order_id, product_id). Which normal form does product_name break?

  4. When is a jsonb or array column a reasonable 1NF exception?

Normalization stores each fact once, so it can't disagree with itself. 1NF: one value per cell, no lists. 2NF and 3NF: every column depends on the key, the whole key and nothing but the key. Lists become rows in a child table; repeated facts move to their own table and are referenced by id.

Part Not started

Denormalization on purpose

Normalization says “store each fact once”. Some copies are still correct, because they’re different facts:

  • Historical values. order_items.unit_price is the price the customer paid, not the product’s current price. The shipping address on an order is where it was sent, even if the customer moves later. An invoice must look the same in five years. These aren’t copies; they’re records of a moment.
  • Cached results for speed. orders.total is the sum of its items. You could compute it with a join and sum every time, but the order list shows thousands of totals per second. Storing it is denormalizationDenormalizationCopying or precomputing data on purpose, usually to make reads cheaper.Open in glossary →: a deliberate copy to make reads cheaper.

A deliberate copy comes with a duty: something must keep it correct. If the app adds an item to an order, it must update orders.total in the same transaction. Otherwise the stored total and the real items drift apart, and nobody notices until a customer is charged the wrong amount.

A good test before adding a copy: “if this copy and the original disagree, which one is right?” If the answer is “the original”, you’ve made a cache, and you need a plan to keep it fresh. If the answer is “both, they mean different things”, it’s a historical fact, and storing it is normalization done right.

Ways to keep a derived copy correct, from tightest to loosest:

  • Same transaction, in the app: update the parent total when items change. Simple, but every code path must do it, including scripts and admin tools.
  • Triggers: the database maintains it regardless of who writes. Hidden logic, harder to test, and hot parent rows become contention points (every item insert updates the same order or the same products.sold_count row).
  • Materialized views: CREATE MATERIALIZED VIEW … ; REFRESH MATERIALIZED VIEW CONCURRENTLY (needs a unique index) for read models that may be minutes stale: dashboards, leaderboards.
  • Events and read models (CQRS): an outbox event updates a separate read store (another table, Elasticsearch, Redis). Eventually consistent; needs idempotent consumers and rebuild tooling.
  • Counters: a single counter row per product serializes all writers. Shard it (N rows, summed on read) or accumulate in Redis and flush.

Flexible attributes: products with different attributes (a shirt has size and color, a laptop has RAM and CPU).

  • Columns: best when attributes are known and queried; sparse NULL columns are cheap in PostgreSQL.
  • EAV (product_attributes(product_id, name, value text)): infinitely flexible, but every value is text, no constraints, and queries need one join per attribute. Usually an anti-pattern.
  • jsonb with a GIN index: flexible, typed values inside, @> containment queries indexed, generated columns or expression indexes for hot keys. The common modern answer.

Predict the output

orders.total is maintained by the app when items change. A support script adds an item with a direct INSERT into order_items. What does the order list show for that order?

INSERT INTO order_items (order_id, product_id, quantity, unit_price)
VALUES (1001, 12, 1, 4.50);

SELECT id, total FROM orders WHERE id = 1001;
-- historical facts stored with the order
CREATE TABLE order_addresses (
    order_id    bigint PRIMARY KEY REFERENCES orders (id) ON DELETE CASCADE,
    full_name   text NOT NULL,
    street      text NOT NULL,
    city        text NOT NULL,
    postal_code text NOT NULL,
    country     char(2) NOT NULL
);

-- a cached total, updated in the same transaction as the items
BEGIN;
INSERT INTO order_items (order_id, product_id, quantity, unit_price) VALUES (1001, 12, 1, 4.50);
UPDATE orders SET total = total + 1 * 4.50 WHERE id = 1001;
COMMIT;

-- flexible attributes as jsonb, indexed for containment queries
ALTER TABLE products ADD COLUMN attributes jsonb NOT NULL DEFAULT '{}';
CREATE INDEX products_attributes ON products USING gin (attributes jsonb_path_ops);
SELECT id, name FROM products WHERE attributes @> '{"color": "red", "size": "M"}';

Practice: addresses

Exercisemedium

Customers with several addresses

Customers can save several addresses (home, work) and pick one as their default. When they order, they choose one of them. Later they may edit or delete a saved address, but old orders must keep showing where they were actually shipped.

Design the tables. Which data is normalized, and which is copied on purpose?

›

Saved addresses are one-to-many from customers. How do you mark exactly one as the default?

›

If an order only pointed at customer_addresses.id, what would happen to it when the customer edits or deletes that address?

SolutionTry it yourself first
CREATE TABLE customer_addresses (
    id          bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    customer_id bigint NOT NULL REFERENCES customers (id),
    label       text NOT NULL,                 -- 'Home', 'Work'
    street      text NOT NULL,
    city        text NOT NULL,
    postal_code text NOT NULL,
    country     char(2) NOT NULL,
    is_default  boolean NOT NULL DEFAULT false
);
-- at most one default per customer
CREATE UNIQUE INDEX one_default_address
    ON customer_addresses (customer_id) WHERE is_default;

CREATE TABLE order_addresses (                 -- a copy, on purpose
    order_id    bigint PRIMARY KEY REFERENCES orders (id),
    street      text NOT NULL,
    city        text NOT NULL,
    postal_code text NOT NULL,
    country     char(2) NOT NULL
);

Saved addresses are normalized: each lives once, and editing it changes it everywhere it’s current. The address on the order is copied when the order is placed, because it records a historical fact: where this parcel went. The partial unique index lets any number of rows be false but only one per customer be true.

Deep diveEAV, jsonb or columns for product attributesInterview favorite

A marketplace sells phones, shoes and furniture; each category has its own attributes, and sellers can add new ones. Three designs:

EAV (attributes(product_id, key, value)): “red shoes in size 42 under 100” becomes a self-join per attribute, values are text (so '100' < '20'), and nothing enforces that shoes have a size. It’s flexible, but every query pays for that and the database can’t help with correctness.

jsonb column: attributes @> '{"color": "red", "size": 42}' uses a GIN index; numeric ranges need expression indexes (((attributes->>'price_eur')::numeric)) or generated columns for the few hot keys. Validation moves to the app or to CHECK (jsonb_typeof(attributes->'size') = 'number'), or to a JSON schema per category. Good default for semi-structured catalogs.

Columns per category (separate tables or sparse nullable columns): strongest typing and simplest SQL, but a migration for every new attribute.

What a senior answer adds: hybrid is normal: core fields as columns (price, category_id, stock), varying ones in jsonb, and a search engine (Elasticsearch, OpenSearch, Typesense) for faceted filtering at scale, fed by events, because “filter by any combination of 30 attributes with counts per value” isn’t an OLTP query in any of the three designs.

  • Historical facts (price paid, address shipped to) aren’t duplicates; caches are. Every cache needs one owner keeping it in sync.
  • Sync options: same transaction, triggers, materialized views (REFRESH … CONCURRENTLY), events/read models. Hot counter rows: shard or buffer.
  • Flexible attributes: columns for core fields, jsonb + GIN (jsonb_path_ops) for the rest, avoid EAV; search engine for faceting.
  • Test: “if they disagree, which is right?”

Check this part

  1. Why does order_items store unit_price instead of always reading products.price?

  2. orders.total is stored for speed. What must happen when an item is added?

  3. Why is EAV usually a poor fit for product attributes?

  4. What does REFRESH MATERIALIZED VIEW CONCURRENTLY require?

Copy data on purpose when it's a historical fact (price paid, shipping address) or a cached result you read far more than you change (order totals, counters). Every copy needs one owner that keeps it in sync: the same transaction, a trigger, a materialized view or events. jsonb usually beats EAV for flexible attributes.

Part Not started

Changing a schema without downtime

Schemas change: a new column, a new table, a renamed field. These changes are written as migrationsDatabase migrationA step that changes an existing database from one schema version to the next without losing its data.Open in glossary →: numbered scripts that a tool runs in order and records as done.

  • Backend: Flyway (V1__create_orders.sql, V2__add_status.sql) or Liquibase.
  • Android: Room migrations (Migration(1, 2)), see Room.
  • iOS: Core Data and SwiftData migrations, see Core Data.

Rules that save you:

  1. Never edit a migration that already ran. Databases that ran the old version won’t run it again; you’d have two different schemas with the same version number. Flyway refuses to start when it notices (“checksum mismatch”). Write a new migration instead.
  2. The old app keeps running during a deploy. For a few minutes, servers with the old code and the new code use the same database. On phones, old app versions keep running for months. A migration must not break the version that’s still out there.

That second rule is why you never just rename a column in one step. The old code still asks for the old name and crashes. Instead you go in small steps, called expand and contract:

  1. Expand: add the new column, keep the old one. Write to both.
  2. Migrate: copy old values into the new column. Switch reads to the new one.
  3. Contract: once no running code uses the old column, drop it.

Each step is a separate deploy, and each one works with the code before and after it.

PostgreSQL lock behavior decides whether a migration is instant or an outage:

  • ADD COLUMN is metadata-only, even with a constant DEFAULT (PostgreSQL 11+). A volatile default (DEFAULT gen_random_uuid(), clock_timestamp()) rewrites the table under an exclusive lock: add the column without it, backfill in batches, then set the default for new rows.
  • SET NOT NULL scans the table under ACCESS EXCLUSIVE. Add CHECK (col IS NOT NULL) NOT VALID, VALIDATE CONSTRAINT (weaker lock, scans without blocking writes), then SET NOT NULL (PostgreSQL 12+ uses the validated check and skips the scan), then drop the check.
  • Foreign keys and checks: ADD CONSTRAINT … NOT VALID then VALIDATE CONSTRAINT separately.
  • Indexes: CREATE INDEX CONCURRENTLY (not inside a transaction; on failure it leaves an INVALID index to drop and retry).
  • Type changes usually rewrite the table (int → bigint on a big table is a project: new column, dual writes, backfill, swap). Some are free (varchar(50) → varchar(100) or text).
  • Every DDL statement waits for ACCESS EXCLUSIVE behind running queries and blocks everyone queued after it: SET lock_timeout = '3s' and retry in the migration tool.
  • Backfills in batches by primary key range, throttled, outside the DDL transaction, idempotent.
  • Mobile: the client database migrates on app update with no rollback; test each upgrade path (Room MigrationTestHelper, testing from every shipped version), and keep server APIs compatible with old app versions for as long as they’re in use.

Predict the output

During a rolling deploy, half the servers run the old code, which reads orders.note. The new code's migration runs first. What happens?

-- V12__rename_note.sql
ALTER TABLE orders RENAME COLUMN note TO delivery_note;
-- V20: add a column (instant), no volatile default
ALTER TABLE orders ADD COLUMN delivery_note text;

-- V21: build an index without blocking writes (runs outside a transaction)
CREATE INDEX CONCURRENTLY orders_delivery_note_not_null ON orders (id) WHERE delivery_note IS NOT NULL;

-- V22: a foreign key added without a long lock, validated separately
ALTER TABLE orders ADD CONSTRAINT orders_coupon_fk
    FOREIGN KEY (coupon_id) REFERENCES coupons (id) NOT VALID;
ALTER TABLE orders VALIDATE CONSTRAINT orders_coupon_fk;

-- every migration: give up quickly instead of queueing the whole app
SET lock_timeout = '3s';

The migration that was “just fixed”

Spot the bugA typo in an old migration

Tap the line with the bug.

-- V7__add_status.sql, ran in production last month.
-- Today a developer edits it to fix the default value:
ALTER TABLE orders ADD COLUMN status text NOT NULL DEFAULT 'NEW';

-- (it used to say DEFAULT 'new')

Deep diveRenaming a column with zero downtimeInterview favorite

Goal: orders.note → orders.delivery_note on a 200-million-row table, with rolling deploys and no errors. The full sequence (see also Zero-downtime schema changes):

  1. Expand (migration + release N): ADD COLUMN delivery_note text (instant). App writes both columns, reads note. Alternatively, a trigger copies note to delivery_note on writes, so old code is covered too.
  2. Backfill (background job): UPDATE orders SET delivery_note = note WHERE id BETWEEN $1 AND $2 AND delivery_note IS DISTINCT FROM note, batches of 10,000, pausing on replica lag.
  3. Switch reads (release N+1): read delivery_note, keep writing both. Verify with a check query that no row differs.
  4. Stop writing the old column (release N+2), once no instance of release N is running anywhere, including workers, cron jobs and other services that read the table.
  5. Contract (migration in N+3): drop the trigger and note. DROP COLUMN is instant in PostgreSQL (space is reclaimed later).

Follow-ups: ORMs that SELECT * or map every column break when a column disappears before the code stops mapping it (step 4 must come first); views and replicas’ consumers (CDC, analytics) also read columns; and if the rename is purely cosmetic, a strong answer questions whether it’s worth five releases at all.

  • Versioned, immutable migrations; fix forward. Old and new code overlap: expand → migrate → contract for renames and type changes.
  • PostgreSQL 11+: ADD COLUMN with a constant default is instant; volatile defaults rewrite. NOT NULL via CHECK … NOT VALID + VALIDATE.
  • CREATE INDEX CONCURRENTLY, ADD CONSTRAINT … NOT VALID, lock_timeout + retry on every DDL. Batched, throttled backfills.
  • Mobile databases migrate on update without rollback: test every upgrade path.

Check this part

  1. You find a mistake in a migration that already ran in production. What do you do?

  2. Why not rename a column in one step during a deploy?

  3. How do you add NOT NULL to a big PostgreSQL column without a long exclusive lock?

  4. Which ADD COLUMN rewrites the whole table in PostgreSQL 11+?

Schema changes go through versioned migrations that are never edited after they run. In production, old and new app versions run side by side, so breaking changes like renames are split into expand, migrate, contract. Watch locks: add columns without volatile defaults, build indexes concurrently, add constraints as NOT VALID and validate later.

Key takeaways

  • Store each fact once: lists become rows in another table, facts about customers live in customers.
  • 3NF in one line: every column depends on the key, the whole key, and nothing but the key.
  • Copy on purpose only for historical facts (price paid, address shipped to) or for speed, and keep caches in sync in the same transaction.
  • Never edit a migration that already ran; write a new one.
  • Rename and other breaking changes in steps: expand, migrate, contract.
  • Normal forms via functional dependencies; arrays/jsonb only for data used as a whole; OLTP in 3NF, analytics in star schemas.
  • Each derived copy needs one owner (transaction, trigger, materialized view, events); avoid EAV, use jsonb + GIN for flexible attributes.
  • Interview schema design: use cases → entities → constraints → indexes → what lives elsewhere.
  • Lock-aware migrations: instant ADD COLUMN, NOT VALID + VALIDATE, CONCURRENTLY, lock_timeout, batched backfills, multi-release renames.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.