Home›Design›Data modeling basics

Data modeling basics

Which keys, types and constraints should a new table start with?

The design docs on this site decide which database each kind of data goes in. This page is one level down: the choices inside a table that are cheap to get right on day one and expensive to change at a hundred million rows.

The 5-minute version

If you read nothing else on this page

  1. Primary key: a bigint identity, or a UUIDv7 if IDs are made outside the database. Random UUIDv4 keys scatter inserts across the whole index.
  2. Money is never a float. Use numeric or decimal, or integer cents.
  3. Store time as an instant with a zone. timestamptz in PostgreSQL; in MySQL, DATETIME in UTC rather than TIMESTAMP, which ends in 2038.
  4. Let the database enforce the rules. NOT NULL, UNIQUE, CHECK and foreign keys catch bugs that application code misses under concurrency.
  5. Normalize first; copy data only for a measured read. In MongoDB, embed what is read together and bounded; reference what grows without limit.

The rest of the page goes deeper, one section per item.

Primary keys

The key decides where every insert lands

ChoiceGoodWatch out
bigint identity / AUTO_INCREMENTSmall (8 bytes), ordered, fast inserts at the right edge of the indexReveals counts and order; hard to generate outside the database
UUIDv7Made anywhere, roughly time-ordered, so inserts stay at the right edge. uuidv7() is built into PostgreSQL 1816 bytes in every index that carries the key (all secondary indexes in InnoDB)
UUIDv4 (random)Made anywhere, reveals nothingEvery insert lands on a random page: more page splits, a bigger working set, more WAL. Watch an index grow shows it
Natural key (email, SKU)MeaningfulValues change; a changed key cascades through every reference. Make it UNIQUE, not the primary key

In MongoDB the default _id is an ObjectId, which is already time-ordered. For tenants, put the tenant first in keys and indexes that are always filtered by tenant.

Types

The smallest type that is always right

DataPostgreSQLMySQLMongoDBWhy
Moneynumeric(12,2)DECIMAL(12,2)Decimal128Floating point cannot represent 0.10 exactly; sums drift
A moment in timetimestamptzDATETIME(6) in UTCDate (UTC)MySQL TIMESTAMP stops at 2038-01-19
Short texttext with a CHECK on length if neededVARCHAR(n)stringIn PostgreSQL varchar(n) and text perform the same
Yes or nobooleanTINYINT(1)/BOOLEANbool
A fixed set of valuesa lookup table, or a CHECKa lookup tablevalidated stringENUM types are awkward to change. In MySQL any change rebuilds the table; in PostgreSQL adding a value is cheap, but removing or renaming one is not
Flexible attributesjsonb with a GIN indexJSON with generated columns indexednativeKeep fields you filter or join on as real columns
Constraints

Rules the database enforces for every client

Application checks run one request at a time; two requests at once both pass a "does this email exist?" check and both insert. A UNIQUE constraint does not have that race. The same goes for stock that must not go below zero (a CHECK) and orders that must point at a real customer (a foreign key).

MongoDB has unique indexes and schema validation ($jsonSchema); it has no foreign keys, so references are checked by the application or not at all.

Normalize, embed, or copy

Where each fact lives

In a relational database each fact lives in one place, and a join puts them together. Copying a value into another table (denormalizing) makes one read faster and every update of that value more work, and a missed update leaves two answers. I copy only when a measured read needs it, and I write down which table is the source of truth.

MongoDB: embed whenReference when
The data is read with the parent nearly every timeIt is read on its own, or by many parents
It is bounded: a few addresses, a handful of line itemsIt grows without limit: comments, events, messages. A document cannot exceed 16 MB, and big documents are slow to update long before that
It changes with the parentIt changes on its own schedule

The design docs apply this per application: product catalog embeds, chat references.

Deletes and history

What happens to a row when it is no longer wanted

ApproachGood forCost
Hard deleteData with no legal or audit need; personal data on requestGone; foreign keys decide what happens to children
Soft delete (deleted_at)Undo, support toolsEvery query and unique index must remember the filter; the table keeps growing
History table or event logAudit, "what did this look like on March 3"Extra writes; see audit and event logs
Partitions dropped by dateLogs, telemetry, anything with retentionNeeds partitioning by time from the start; dropping a partition is instant
Your turn

A new orders table: id, customer, status, total, created time, and a list of line items. Write down the columns, types and constraints you would start with, in the engine you use.

Write your answer down first. Then open mine.

Show my answer

PostgreSQL: id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, customer_id bigint NOT NULL REFERENCES customers(id) plus an index on it, status text NOT NULL CHECK (status IN ('new','paid','shipped','cancelled')), total numeric(12,2) NOT NULL CHECK (total >= 0), created_at timestamptz NOT NULL DEFAULT now(). Line items in their own table with order_id referencing orders, indexed.

MySQL: the same shape, with BIGINT AUTO_INCREMENT, DECIMAL(12,2) and DATETIME(6) stored in UTC.

MongoDB: one document per order with the line items embedded (bounded, read together, frozen once paid), customer_id as a reference, an index on { customer_id: 1, created_at: -1 }, and a $jsonSchema validator requiring the fields.

Connected

Where this shows up

The same mechanism, keys and ids, indexes and plans, elsewhere on the site: in real incidents, in measurements, and in designs.

Check yourself · 4 questions

Check yourself

Pick an answer. You will see whether it is right, and why.

1. Why are random UUIDv4 primary keys slow for inserts at scale?

2. Two requests check that an email is free and both insert it. What prevents the duplicate?

3. Which type for prices?

4. A user's comments can grow without limit. Embed them in the user document?

Part 3 of 4 · Design · 24 pagesAll pages

Which database does my application need? What kind of application data goes in which database, and why, as design docs, plus the anti-patterns and the decisions behind them.