Database Denormalization
What you will learn
- What denormalization is, and what it is not
- Common good reasons for it
- How a stored copy drifts from the truth
- Ways to keep copies correct
- A checklist before you denormalize
1. What it is
Denormalization means deliberately storing a fact in more than one place, or storing a value that could be calculated, to make reads simpler or faster. It is a trade: faster or simpler reads in exchange for the risk and work of keeping the copies in agreement.
It is not the same as never normalizing. The rule is: normalize first, then denormalize only for a reason you can name.
2. Good reasons
| Reason | Example |
|---|---|
| History must not change | an order line keeps the price at the time of sale, even if the product price changes later |
| Expensive calculation | a stored order total or a customer's order count, used on every page |
| Reporting | a wide table prepared for analysis (chapter 13), refreshed on a schedule |
| Simplicity of reading | a copied name for a search page |
The first one is not really "redundancy": the price on the order line is a different fact ("what we charged") from the current product price, and it follows its own rule (lesson 5.4).
3. A stored total that drifts
This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). It adds small tables of its own to your browser's copy; run the examples from top to bottom, and press Reset data to start again.
A stored total can always be calculated from the data it summarises. In the Shop, the total of an order is the sum of its lines (order_items):
A stored total can always be calculated from the data it summarises. In the Bank, the amount paid on a loan is the sum of its payments (loan_payments):
A stored total can always be calculated from the data it summarises. In the School, the points given for an assignment are the sum of the submissions (submissions):
SELECT order_id, ROUND(SUM(quantity * unit_price), 2) AS total
FROM order_items
WHERE order_id IN (1, 2)
GROUP BY order_id
ORDER BY order_id;
order_id total
-------- ------
1 107.55
2 48.0
(2 rows)
SELECT loan_id, SUM(amount_cents) AS paid_cents
FROM loan_payments
WHERE loan_id IN (1, 2)
GROUP BY loan_id
ORDER BY loan_id;
loan_id paid_cents
------- ----------
1 296892
2 105000
(2 rows)
SELECT assignment_id, ROUND(SUM(points), 1) AS total_points
FROM submissions
WHERE assignment_id IN (1, 2)
GROUP BY assignment_id
ORDER BY assignment_id;
assignment_id total_points
------------- ------------
1 969.2
2 993.5
(2 rows)
If this runs on every page of a busy system, you might store the result in a table of its own:
CREATE TABLE order_totals AS
SELECT order_id, ROUND(SUM(quantity * unit_price), 2) AS total
FROM order_items
WHERE order_id IN (1, 2)
GROUP BY order_id;
SELECT * FROM order_totals ORDER BY order_id;
order_id total
-------- ------
1 107.55
2 48.0
(2 rows)
CREATE TABLE loan_paid AS
SELECT loan_id, SUM(amount_cents) AS paid_cents
FROM loan_payments
WHERE loan_id IN (1, 2)
GROUP BY loan_id;
SELECT * FROM loan_paid ORDER BY loan_id;
loan_id paid_cents
------- ----------
1 296892
2 105000
(2 rows)
CREATE TABLE assignment_points AS
SELECT assignment_id, ROUND(SUM(points), 1) AS total_points
FROM submissions
WHERE assignment_id IN (1, 2)
GROUP BY assignment_id;
SELECT * FROM assignment_points ORDER BY assignment_id;
assignment_id total_points
------------- ------------
1 969.2
2 993.5
(2 rows)
Reads are now trivial. But the stored copy can drift: change a source row and forget to update the copy.
UPDATE order_items SET quantity = 5 WHERE order_id = 1 AND line_no = 1;
SELECT c.order_id, c.total AS stored,
(SELECT ROUND(SUM(quantity * unit_price), 2) FROM order_items WHERE order_id = c.order_id) AS real
FROM order_totals c
ORDER BY c.order_id;
order_id stored real
-------- ------ ------
1 107.55 225.55
2 48.0 48.0
(2 rows)
UPDATE loan_payments SET amount_cents = 9000 WHERE payment_id = 1;
SELECT c.loan_id, c.paid_cents AS stored,
(SELECT SUM(amount_cents) FROM loan_payments WHERE loan_id = c.loan_id) AS real
FROM loan_paid c
ORDER BY c.loan_id;
loan_id stored real
------- ------ ------
1 296892 297645
2 105000 105000
(2 rows)
UPDATE submissions SET points = 90 WHERE assignment_id = 1 AND student_id = 16;
SELECT c.assignment_id, c.total_points AS stored,
(SELECT ROUND(SUM(points), 1) FROM submissions WHERE assignment_id = c.assignment_id) AS real
FROM assignment_points c
ORDER BY c.assignment_id;
assignment_id stored real
------------- ------ ------
1 969.2 1011.4
2 993.5 993.5
(2 rows)
The first key now has a stored value that no longer matches the real one. This is the update anomaly again, now created on purpose, so you must prevent it.
4. Keeping copies correct
| Method | How |
|---|---|
| Database trigger | the database updates the copy whenever the source changes |
| Application code | one function is the only place that changes the source, and it also updates the copy (risky if another program writes to the database) |
| Periodic rebuild | a scheduled job recalculates the copies; fine for reports that may be a few hours old |
| Check query | a query like the one above, run regularly, that finds rows where copy and truth differ |
Here is a fresh copy kept right by three triggers (SQLite syntax; other systems write triggers slightly differently). COALESCE makes a key with no source rows get 0 instead of NULL:
CREATE TABLE order_totals_live AS
SELECT order_id, ROUND(COALESCE(SUM(quantity * unit_price), 0), 2) AS total
FROM order_items
WHERE order_id IN (1, 2)
GROUP BY order_id;
CREATE TRIGGER order_items_ins AFTER INSERT ON order_items BEGIN
UPDATE order_totals_live SET total = (SELECT ROUND(COALESCE(SUM(quantity * unit_price), 0), 2) FROM order_items WHERE order_id = NEW.order_id) WHERE order_id = NEW.order_id;
END;
CREATE TRIGGER order_items_upd AFTER UPDATE ON order_items BEGIN
UPDATE order_totals_live SET total = (SELECT ROUND(COALESCE(SUM(quantity * unit_price), 0), 2) FROM order_items WHERE order_id = NEW.order_id) WHERE order_id = NEW.order_id;
END;
CREATE TRIGGER order_items_del AFTER DELETE ON order_items BEGIN
UPDATE order_totals_live SET total = (SELECT ROUND(COALESCE(SUM(quantity * unit_price), 0), 2) FROM order_items WHERE order_id = OLD.order_id) WHERE order_id = OLD.order_id;
END;
SELECT * FROM order_totals_live WHERE order_id = 1;
order_id total
-------- ------
1 225.55
(1 row)
Now change the source three ways and watch the first value after each change. An insert:
INSERT INTO order_items VALUES (1, 9, 5, 2, 10.0);
SELECT * FROM order_totals_live WHERE order_id = 1;
order_id total
-------- ------
1 245.55
(1 row)
An update:
UPDATE order_items SET quantity = 5 WHERE order_id = 1 AND line_no = 1;
SELECT * FROM order_totals_live WHERE order_id = 1;
order_id total
-------- ------
1 245.55
(1 row)
A delete:
DELETE FROM order_items WHERE order_id = 1 AND line_no = 9;
SELECT * FROM order_totals_live WHERE order_id = 1;
order_id total
-------- ------
1 225.55
(1 row)
CREATE TABLE loan_paid_live AS
SELECT loan_id, COALESCE(SUM(amount_cents), 0) AS paid_cents
FROM loan_payments
WHERE loan_id IN (1, 2)
GROUP BY loan_id;
CREATE TRIGGER loan_payments_ins AFTER INSERT ON loan_payments BEGIN
UPDATE loan_paid_live SET paid_cents = (SELECT COALESCE(SUM(amount_cents), 0) FROM loan_payments WHERE loan_id = NEW.loan_id) WHERE loan_id = NEW.loan_id;
END;
CREATE TRIGGER loan_payments_upd AFTER UPDATE ON loan_payments BEGIN
UPDATE loan_paid_live SET paid_cents = (SELECT COALESCE(SUM(amount_cents), 0) FROM loan_payments WHERE loan_id = NEW.loan_id) WHERE loan_id = NEW.loan_id;
END;
CREATE TRIGGER loan_payments_del AFTER DELETE ON loan_payments BEGIN
UPDATE loan_paid_live SET paid_cents = (SELECT COALESCE(SUM(amount_cents), 0) FROM loan_payments WHERE loan_id = OLD.loan_id) WHERE loan_id = OLD.loan_id;
END;
SELECT * FROM loan_paid_live WHERE loan_id = 1;
loan_id paid_cents
------- ----------
1 297645
(1 row)
Now change the source three ways and watch the first value after each change. An insert:
INSERT INTO loan_payments (loan_id, paid_on, amount_cents) VALUES (1, '2026-10-01', 5000);
SELECT * FROM loan_paid_live WHERE loan_id = 1;
loan_id paid_cents
------- ----------
1 302645
(1 row)
An update:
UPDATE loan_payments SET amount_cents = 9000 WHERE payment_id = 1;
SELECT * FROM loan_paid_live WHERE loan_id = 1;
loan_id paid_cents
------- ----------
1 302645
(1 row)
A delete:
DELETE FROM loan_payments WHERE loan_id = 1 AND paid_on = '2026-10-01';
SELECT * FROM loan_paid_live WHERE loan_id = 1;
loan_id paid_cents
------- ----------
1 297645
(1 row)
CREATE TABLE assignment_points_live AS
SELECT assignment_id, ROUND(COALESCE(SUM(points), 0), 1) AS total_points
FROM submissions
WHERE assignment_id IN (1, 2)
GROUP BY assignment_id;
CREATE TRIGGER submissions_ins AFTER INSERT ON submissions BEGIN
UPDATE assignment_points_live SET total_points = (SELECT ROUND(COALESCE(SUM(points), 0), 1) FROM submissions WHERE assignment_id = NEW.assignment_id) WHERE assignment_id = NEW.assignment_id;
END;
CREATE TRIGGER submissions_upd AFTER UPDATE ON submissions BEGIN
UPDATE assignment_points_live SET total_points = (SELECT ROUND(COALESCE(SUM(points), 0), 1) FROM submissions WHERE assignment_id = NEW.assignment_id) WHERE assignment_id = NEW.assignment_id;
END;
CREATE TRIGGER submissions_del AFTER DELETE ON submissions BEGIN
UPDATE assignment_points_live SET total_points = (SELECT ROUND(COALESCE(SUM(points), 0), 1) FROM submissions WHERE assignment_id = OLD.assignment_id) WHERE assignment_id = OLD.assignment_id;
END;
SELECT * FROM assignment_points_live WHERE assignment_id = 1;
assignment_id total_points
------------- ------------
1 1011.4
(1 row)
Now change the source three ways and watch the first value after each change. An insert:
INSERT INTO submissions VALUES (1, 360, '2025-11-20', 10.0);
SELECT * FROM assignment_points_live WHERE assignment_id = 1;
assignment_id total_points
------------- ------------
1 1021.4
(1 row)
An update:
UPDATE submissions SET points = 90 WHERE assignment_id = 1 AND student_id = 16;
SELECT * FROM assignment_points_live WHERE assignment_id = 1;
assignment_id total_points
------------- ------------
1 1021.4
(1 row)
A delete:
DELETE FROM submissions WHERE assignment_id = 1 AND student_id = 360;
SELECT * FROM assignment_points_live WHERE assignment_id = 1;
assignment_id total_points
------------- ------------
1 1011.4
(1 row)
The stored value follows every insert, update and delete. Three triggers to protect one stored number is the real cost of denormalizing. Some databases offer built-in alternatives such as generated columns and materialized views (lessons 11.3 and 11.6).
Worked example: should we store it?
A shop shows "number of orders" on each customer's page, and customers have thousands of orders.
| Question | Answer |
|---|---|
| Is the calculation slow? | COUNT(*) over thousands of rows per page view: maybe, measure it first |
| How often does the source change? | a few times a day per customer: cheap to maintain |
| What if the copy is wrong? | a wrong number on a page: annoying, not harmful |
| Can we rebuild it? | yes, with one query |
Decision: measure first; if it is slow, store order_count and update it in the same transaction (chapter 6) as the order insert. For a total used in money calculations, we would be stricter. Data is made up.
Common mistakes
- Denormalizing before measuring. Databases are often fast enough; try an index first (chapter 7).
- Having no plan to keep copies correct. A copy without a rule for updating it is a bug waiting to happen.
- Updating a copy in a different transaction from its source, so a failure leaves them out of step.
- Denormalizing to avoid learning joins.
Key takeaways
- Denormalization is a deliberate, named trade: easier or faster reads for more work keeping copies right.
- Normalize first; denormalize for a measured reason.
- Good reasons: history snapshots, expensive repeated calculations, reporting tables.
- Keep copies correct with triggers, one controlled code path, scheduled rebuilds or check queries.
- Always have a query that finds copies that disagree with the truth.
Practice
1. What is denormalization?
Show answer
Deliberately storing a fact or a calculable value in more than one place to make reads simpler or faster.
2. Why does an order line keep its own price?
Show answer
It records the price charged at the time of sale, which must not change when the product price changes later.
3. What was wrong with the stored copy after the source row was changed?
Show answer
The stored value no longer matched the sum of the source rows (for example 107.55 stored against 225.55 real in the Shop): the copy had drifted.
4. Name two ways to keep a stored total correct.
Show answer
Any two of: a trigger, one controlled code path that updates both, a scheduled rebuild, a regular check query.
5. Why should you measure before denormalizing?
Show answer
The query may already be fast enough or fixable with an index, and denormalizing adds permanent maintenance cost.
6. The trigger in the lesson handles only updates. What else is needed?
Show answer
Triggers (or equivalent code) for inserting and deleting order lines; the lesson's last block shows all three.