Data modeling explained: normalization, denormalization, OLTP vs OLAP and query-driven design

Picking a database is half the job. The other half is the shape of your data. Learn when to store each fact once and when to copy it, why order history needs snapshots, how analytics data is shaped differently, and why NoSQL schemas start from your queries.

A balance scale. On the left pan sits one neat box labelled "one fact, one place" under the word Normalized, with the note "easy to keep correct". On the right pan sit several copies of the same box under the word Denormalized, with the note "fast to read". A sign above asks "Copy it, or join it?"
Fig. 1 — Every data model sits somewhere on this scale. Store each fact once and keep it correct, or copy it where it's read and keep it fast.

A customer emails support: “My invoice from March says I paid ₹1,499 for these headphones. I paid ₹1,299.”

You check. They’re right. The order_items table only stored a product_id, and the invoice page joined to products to show the price. Last week the price went up, so every past invoice for those headphones changed too. History was rewritten by an ordinary price update.

Nothing was wrong with the database. The shape of the data was wrong. That’s data modeling: deciding how real-world things and their relationships become tables, documents and keys. In the previous part we picked the right database. Now we decide what goes inside it.

“A good schema in the “wrong” database often beats a bad schema in the right one.”

Start with the questions, not the tables

Most people start by listing things: users, products, orders, reviews. That’s useful, but it’s only half the picture. The other half is what you’ll ask the data, also called your access patterns:

  • Show a user’s orders, newest first.
  • List all products in a category.
  • Show a product’s average rating.
  • Total revenue per day for the finance team.

Your model decides how fast each of these runs, how much data you copy around, and how much code you need to keep it all correct. Write the questions down first. Every choice below is answered by them.

Normalization: store each fact once

Normalization means every fact lives in exactly one place. Here’s the opposite, a table that copies everything into every order:

-- ❌ Every order repeats the user's details and the product's details
CREATE TABLE orders (
    order_id      BIGINT,
    user_name     VARCHAR(100),
    user_email    VARCHAR(255),   -- copied into every order
    product_name  VARCHAR(200),   -- copied into every order
    quantity      INT
);

When a user changes their email, you must update every one of their orders. Miss one, and the data disagrees with itself. Normalized, each thing gets its own table and orders just point to them by ID:

CREATE TABLE users       (user_id BIGINT PRIMARY KEY, name VARCHAR(100), email VARCHAR(255) UNIQUE);
CREATE TABLE products    (product_id BIGINT PRIMARY KEY, name VARCHAR(200), price DECIMAL(10,2));
CREATE TABLE orders      (order_id BIGINT PRIMARY KEY, user_id BIGINT REFERENCES users, created_at TIMESTAMP);
CREATE TABLE order_items (order_id BIGINT REFERENCES orders, product_id BIGINT REFERENCES products,
                          quantity INT, PRIMARY KEY (order_id, product_id));

Now an email change is one update in one row. The cost: reading a full order needs joins across four tables.

You’ll hear about normal forms. You don’t need to memorise them. In short:

Rule Means Broken by
1NF One value per cell product_ids = "1,2,3" in one column
2NF Every column depends on the whole key product_name in order_items (it depends only on product_id)
3NF No column depends on another non-key column city stored next to zip_code in users (city follows from zip)

Denormalization: copy on purpose, for speed

At scale, joins and counts get expensive. Denormalization stores a copy of data where it’s read, trading extra storage and extra write work for fast reads.

Left, normalized: users, orders and products are separate boxes. The user's email lives only in the users box. Changing the email is one update, but showing an order needs joins across three tables. Right, denormalized: each order box carries its own copy of the user's name and email. Showing an order is one read, but changing the email means updating every copy, and a missed copy leaves the data out of sync.
Normalized: one update, many joins. Denormalized: one read, many updates.
Normalized Denormalized
Reads Slower (joins) Fast (one place)
Writes Fast (one place) Slower (update every copy)
Keeping it correct Easy Your job
Storage Small Bigger
Typical home Transactional apps (OLTP) Analytics (OLAP), NoSQL, caches

The golden rule: normalize first, denormalize when you have a proven slow read. Three patterns cover most cases.

1. Stored counts. A profile page showing followers, posts and likes could count three tables on every view. Instead, keep the counts in the users row and bump them in the same transaction as the change:

// Java · Spring: the follow and both counts commit together, or not at all
@Transactional
public void follow(long followerId, long followingId) {
    follows.save(new Follow(followerId, followingId));
    users.incrementFollowerCount(followingId);   // UPDATE users SET follower_count = follower_count + 1 ...
    users.incrementFollowingCount(followerId);
}

2. Snapshots. Copy the values as they were at the moment something happened. This is what fixes the invoice bug from the opening.

3. Materialized views. Let the database pre-compute a heavy query and store the result, then refresh it on a schedule:

CREATE MATERIALIZED VIEW daily_revenue AS
SELECT DATE(created_at) AS day, SUM(total_amount) AS revenue, COUNT(*) AS orders
FROM orders GROUP BY DATE(created_at);

REFRESH MATERIALIZED VIEW daily_revenue;   -- e.g. every hour

Snapshots: copying that isn’t really duplication

Back to the invoice. The price on an invoice isn’t “the product’s price”. It’s “the price on the day you bought it”. Those are two different facts, and they need two different homes.

A timeline. In March the headphones cost 1,299 rupees, and a customer buys them. Later the price changes to 1,499. Top row: the invoice joins to the products table, so it now shows 1,499, which is wrong. Bottom row: the order item stored price_at_purchase = 1,299 when the order was placed, so the invoice still shows 1,299, which is right.
An order should record what was true when it happened. Joining to today's data rewrites history.
CREATE TABLE order_items (
    order_id          BIGINT REFERENCES orders,
    product_id        BIGINT REFERENCES products,   -- still linked, for "view product"
    product_name      VARCHAR(200),                 -- snapshot: the product may be renamed
    price_at_purchase DECIMAL(10,2) NOT NULL,       -- snapshot: the price may change
    quantity          INT NOT NULL
);

The same goes for the shipping address on an order (the user may move) and the email it was sent to. A good test: if this value changes tomorrow, should old records change with it? If no, take a snapshot.

OLTP vs OLAP: running the business vs analysing it

The same company has two very different jobs for its data, and they want different shapes.

OLTP (transactions) OLAP (analytics)
Job Run the business Understand the business
Example Place an order, update stock “Revenue by category per month”
Queries Short, touch a few rows Long, scan millions of rows
Users Thousands of customers A few analysts and dashboards
Writes Constant, small Loaded in batches
Shape Normalized Denormalized: star schema
Databases PostgreSQL, MySQL ClickHouse, Snowflake, BigQuery, Redshift

Analytics data is usually shaped as a star schema: one big fact table of events (each sale, with its numbers) surrounded by dimension tables that describe them (date, product, customer).

A star schema. In the centre, a fact_sales table with date_key, product_key, customer_key, quantity, revenue and profit. Around it, three dimension tables: dim_date with date, month, quarter and year; dim_product with name, category and brand; dim_customer with city, country and segment. A sample question underneath: revenue by category by quarter, which joins the fact table to two dimensions and sums revenue.
Facts in the middle, descriptions around them. Any business question is one hop from the centre.

Every analytics question becomes “join the facts to one or two dimensions, then group and sum”. Analysts find it easy to read, and columnar databases are built to run it fast.

Don’t run these reports on your OLTP database. A query scanning a year of orders will compete with checkout for CPU and disk. Copy the data to an analytics store (often overnight, or streamed) and query it there.

Query-driven design: the NoSQL way

In a relational database you model the things and let joins answer any question later. Most NoSQL databases don’t join, so you flip it: design one shape per question.

Take a chat app on Cassandra. The question “latest 50 messages in a chat” gets a table keyed by chat:

CREATE TABLE messages_by_chat (
    chat_id   UUID,
    sent_at   TIMESTAMP,
    sender_id UUID,
    body      TEXT,
    PRIMARY KEY (chat_id, sent_at)          -- partition by chat, sorted by time
) WITH CLUSTERING ORDER BY (sent_at DESC);

Now someone asks for “all messages sent by one user”. This table can’t answer it without scanning everything. The answer isn’t an index; it’s a second table shaped for that question, written at the same time:

On the left, a list of questions. Question 1: latest messages in a chat. Question 2: all messages sent by a user. One incoming message is written twice: to messages_by_chat, partitioned by chat_id, and to messages_by_user, partitioned by sender_id. Each question reads exactly one partition of its own table. A note says: more writes and more storage, but every read is one fast lookup.
Relational: model the things, join later. Wide-column and key-value: one table per question, written up front.

Feeds work the same way. Instead of “find everyone I follow, fetch their posts, merge and sort” on every page load, many systems fan out on write: when someone posts, the post ID is pushed into each follower’s ready-made feed (often a Redis sorted set). Reading a feed becomes one lookup. The cost moves to the write, which gets expensive for accounts with millions of followers, so big systems mix both approaches.

For document databases, the same thinking drives the embed or reference choice:

  • Embed when it’s one-to-few, read together, and rarely changes on its own (a user’s addresses).
  • Reference when it’s one-to-many, grows without limit, or changes on its own (a user’s orders). Documents have size limits; MongoDB’s is 16 MB.
Database Modeling style
PostgreSQL / MySQL Normalize, then denormalize hot spots
MongoDB Embed or reference, by how you read it
Cassandra One table per query
Redis Store the finished answer, ready to serve
Analytics store Star schema, heavily denormalized

What breaks, and how to fix it

What breaks Why The fix
Counts drift (follower_count says 1,000, real count 995) Count updated outside the transaction, or a bug Update in the same transaction, plus a nightly reconciliation job
The N+1 query Loading a list, then one query per item in a loop Fetch together (JOIN FETCH, IN (...)), or denormalize the field you need
History rewritten Old records join to today’s values Snapshot values that belong to the moment
Copies out of sync A denormalized field was updated in one place only Update copies from one place: a transaction, or an event every copy listens to
Reports slow down checkout Analytics queries running on the OLTP database Move them to a replica or an analytics store

Puzzle 1: the 1,001 queries

This is the N+1 problem: 1 query for the orders, then 1,000 more for the users, one per loop. Each takes a couple of milliseconds, but a thousand round trips add up. ORMs hide it well, since order.getUser() on a lazy relation does the same thing behind your back.

Fix it by fetching together: one query with JOIN FETCH o.user, or load all the users at once with findAllById(userIds). Or, if the page only needs the name, snapshot customer_name onto the order. Turn on SQL logging in development and N+1 jumps out immediately.

Puzzle 2: where did 5 followers go?

Somewhere, the count and the real data were changed separately. Maybe the count was bumped after the transaction, and the follow insert then failed. Maybe two requests did “read count, add one, write it back” at once and one lost. Or an unfollow path forgot to decrement.

Prevent it by changing both in one transaction, using an atomic update (SET follower_count = follower_count + 1, never read-then-write). Then accept that denormalized data can still drift through bugs, and run a scheduled reconciliation job that recounts and repairs. The source of truth is the follows table; the count is just a fast copy.

Puzzle 3: what did it cost on 1 January?

You can’t answer it: the old price is gone. Keep history instead of overwriting it. Three options:

  • Price history table: each change is a new row with effective_from. The current price is the latest row; a past price is the latest row before that date. Simple and complete.
  • Validity ranges: rows carry valid_from and valid_to. A change closes the current row and inserts a new one. Queries read naturally: “where the date is between valid_from and valid_to”.
  • Daily snapshots: a nightly job copies all prices into a dated table. Easiest to build, but uses the most storage and only knows one price per day.

Key takeaways

  1. Start from your questions. Access patterns drive every modeling choice.
  2. Normalize first. One fact in one place keeps data correct and writes simple.
  3. Denormalize on proof. Stored counts, snapshots and materialized views speed up reads, but keeping copies correct becomes your job.
  4. Snapshots aren’t duplication. The price when ordered is a different fact from the price today.
  5. OLTP and OLAP want different shapes. Normalized for running the business, star schema for analysing it, in separate stores.
  6. NoSQL is query-driven. One table or document shape per question, written up front.

That completes the Data storage & data modeling thread: which database to use, and how to shape the data inside it. Next comes the question every growing system faces: what to do when one database machine isn’t enough, and the data has to be partitioned and sharded.

Comments

LEAVE A COMMENT
No sign-up. Comments appear after a quick review.