Data Modeling
From Concepts to Tables
A model is refined in three passes. Each pass answers a different question, and skipping one usually shows up later as a schema that is either vague or impossible to change.
Conceptual, Logical, Physical
| Level | Question | Output |
|---|---|---|
| Conceptual | What things does the business care about, and how are they related? | Entities and relationships, no data types. |
| Logical | Which attributes, keys and rules does each entity have? | Normalized tables, keys, cardinalities, constraints. |
| Physical | How is it stored efficiently on a specific engine? | DDL with types, indexes, partitions, schemas. |
The logical model is the contract. It should still be valid if the engine changes; the physical model is where engine-specific choices such as jsonb, partitioning or tablespaces belong.
Entities and Attributes
An entity is a set of things with a shared identity rule: customers, orders, products. Name tables after the thing a single row represents, consistently singular or plural across the schema. Each attribute should hold one fact about that one thing. If a column name contains a number (phone1, phone2) or a column holds a list, the model is missing an entity.
Keys and Identity
Every table needs a primary key: a column or set of columns that is unique, never null, and stable over the life of the row. Choosing it well is the most consequential decision in the model, because every foreign key copies it.
Natural vs Surrogate Keys
A natural key comes from the real world: an ISO country code, an ISBN. A surrogate key is generated by the database and has no meaning. Natural keys are attractive but often less stable than they look — e-mail addresses change, and national identifiers get reissued or contain errors. A common, robust pattern is a surrogate primary key plus a unique constraint on the natural key, so both identity and business uniqueness are enforced:
-- Surrogate key for joins; the natural key is still enforced as unique.
CREATE TABLE customer (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL,
full_name text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT customer_email_uq UNIQUE (email)
);
GENERATED ALWAYS AS IDENTITY is the SQL-standard replacement for serial in PostgreSQL; Oracle 12c and later supports the same clause. Use bigint for keys of tables that may grow large — running out of a 32-bit sequence in production is an outage that is entirely preventable.
Composite and Alternate Keys
A composite key combines columns: an order line is identified by its order and its line number. Composite keys are natural for junction and child tables, and they make the dependency explicit. Any other column set that is also unique is an alternate key; declare it with UNIQUE so the database, not application code, guarantees it.
Implementing Relationships
Cardinality on the diagram becomes a concrete structure in the schema. A foreign key is a promise that the referenced row exists, enforced on every insert, update and delete.
One-to-Many, Many-to-Many, One-to-One
- One-to-many: a foreign key on the many side, for example
customer_order.customer_id. - Many-to-many: a junction table whose primary key combines both foreign keys; attributes of the relationship itself (quantity, role, date) live there too.
- One-to-one: a foreign key that is also unique, or that is the child's primary key. Use it to separate optional or rarely read data, not by default.
CREATE TABLE product (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
sku text NOT NULL UNIQUE,
price numeric(12,2) NOT NULL CHECK (price >= 0)
);
-- One customer has many orders.
CREATE TABLE customer_order (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id bigint NOT NULL REFERENCES customer (id),
status text NOT NULL DEFAULT 'open'
CHECK (status IN ('open', 'paid', 'shipped', 'cancelled')),
ordered_at timestamptz NOT NULL DEFAULT now()
);
-- Orders and products are many-to-many; the line carries the relationship's data.
CREATE TABLE order_line (
order_id bigint NOT NULL REFERENCES customer_order (id) ON DELETE CASCADE,
line_no integer NOT NULL,
product_id bigint NOT NULL REFERENCES product (id),
quantity integer NOT NULL CHECK (quantity > 0),
unit_price numeric(12,2) NOT NULL,
PRIMARY KEY (order_id, line_no)
);
Choose Referential Actions
The ON DELETE clause decides what happens to children when a parent disappears. The default (NO ACTION) rejects the delete, which is the safe choice for most business data. Use CASCADE only when the child has no meaning without the parent — order lines without an order — and never across aggregates, where one delete could silently remove large amounts of history. SET NULL suits optional links such as an assigned support agent. Note that PostgreSQL does not index foreign-key columns automatically; see Indexing.
Constraints and Domains
Constraints are rules the database enforces on every write, from every client, forever. A rule that only lives in application code will eventually be bypassed by a script, a second application or a manual fix. Declare the rule once, in the schema.
NOT NULL, CHECK and UNIQUE
Make columns NOT NULL unless absence is a meaningful state, and if it is, document what NULL means. Use CHECK for value ranges and allowed states, and table-level checks for rules that span columns:
CREATE TABLE price_period (
product_id bigint NOT NULL REFERENCES product (id),
valid_from date NOT NULL,
valid_to date, -- NULL means "still current"
price numeric(12,2) NOT NULL CHECK (price >= 0),
PRIMARY KEY (product_id, valid_from),
CONSTRAINT price_period_range_ck CHECK (valid_to IS NULL OR valid_to > valid_from)
);
Name constraints explicitly. A violation then reports price_period_range_ck instead of a generated name, which makes errors readable in application logs and migrations reviewable.
Reusable Domains
A domain is a named data type with built-in rules. When the same concept appears in many tables — an e-mail address, a currency amount, a percentage — a domain keeps the definition in one place:
CREATE DOMAIN email_address AS text
CHECK (VALUE ~ '^[^@\s]+@[^@\s]+\.[^@\s]+$');
CREATE DOMAIN money_amount AS numeric(12,2)
CHECK (VALUE >= 0);
-- Columns declared with a domain inherit its rules automatically.
ALTER TABLE customer ALTER COLUMN email TYPE email_address;
CREATE DOMAIN is part of the SQL standard and supported by PostgreSQL; other engines approximate it with check constraints or user-defined types. Keep domain checks simple: a domain validates shape, not truth — it cannot prove an e-mail address exists.
Schema Strategy
A schema lives longer than the application that created it. Strategy is about keeping it understandable and changeable as tables, teams and tenants multiply.
Naming and Namespaces
Pick a convention and enforce it in review: lowercase snake_case avoids quoted identifiers, foreign keys named <table>_id make joins obvious, and constraint names carry a suffix (_pk, _fk, _uq, _ck). Group related tables into schemas (sales, billing, audit); schemas also become the unit for granting privileges, as shown in Security & Access Control.
Evolve the Schema with Migrations
Every schema change should be a versioned migration script in source control, applied by a tool such as Flyway, Liquibase, Alembic or the framework's own migrator — never an ad hoc statement typed into production. For tables in active use, prefer expand and contract: add the new column or table, deploy code that writes both, backfill, switch reads, and only then drop the old structure. Each step is backward compatible, so a deployment can be rolled back without restoring data.
Recognize Modeling Anti-Patterns
- Entity-attribute-value tables (
entity, attribute, value) discard types and constraints. Use real columns, or a typedjsonbcolumn for genuinely open-ended attributes. - Polymorphic foreign keys (
owner_type, owner_id) cannot be enforced by the database. Use one nullable foreign key per target with a check that exactly one is set, or separate tables. - Comma-separated lists in a column break indexing, joins and integrity. They are a missing junction table.
- Magic values such as
1900-01-01meaning “unknown” hide nulls from every query that forgets the convention.
Practice Lab
Use a local PostgreSQL instance or a free hosted sandbox. Keep every statement in a numbered migration file.
Model a Small Domain
- Choose a domain with at least one many-to-many relationship, such as a library (books, authors, loans, members).
- Write the logical model first: entities, keys, cardinalities and rules, with no SQL.
- Translate it into DDL with named constraints, a domain for one repeated concept, and deliberate
ON DELETEactions. - Try to insert ten rows that violate a business rule; every one should be rejected by the database itself.
Evolve It Safely
- Requirement change: a member may now have several phone numbers. Write the expand migration that adds a child table.
- Write a backfill statement that moves existing numbers into it.
- Write the contract migration that drops the old column, and explain in a comment why it must ship separately.