Normalisation and denormalisation
One fact, one place
Section titled “One fact, one place”An online shop stores each order as one wide row: the order number, the customer’s name, the customer’s delivery address, the product, the price. It is convenient. One read returns everything the order page needs.
Now a customer moves. Their address appears in every order they ever placed, and every one of those rows has to change. If one is missed, the same customer now has two addresses depending on which order you look at, and nothing in the database can tell which is right. William Kent’s classic guide to normal forms describes exactly this problem: when a fact is repeated, because of the redundancy the data might become inconsistent, with different records showing different values for the same thing.
Normalisation is the discipline that prevents it: organise the tables so that each fact is stored once, and let tables refer to each other by key. Kent’s mnemonic for the rule is that every non-key field must be a fact about the key, the whole key and nothing but the key. In the shop, the address is a fact about the customer, so it belongs in a customers table, and an order holds only the customer’s ID.
Mental model. Normalisation puts each fact in one place, so that it can only disagree with itself if the place is wrong. Denormalisation puts copies where they are read, and you accept that copies can disagree.
The same split makes other mistakes impossible too. With the customer’s data inside the orders, you could not record a customer who has not ordered yet, and deleting a customer’s last order would erase their address. In a customers table neither happens. PostgreSQL’s foreign key constraint closes the loop: the values in the order’s customer_id column must match a row of the customers table, so an order cannot point at a customer that does not exist.
What a repeated fact costs
Section titled “What a repeated fact costs”Take 10 million orders from 1 million customers, so each customer has 10 orders on average, and an address of 200 bytes.
- Space. Repeated on every order, the address takes 10,000,000 × 200 = 2,000,000,000 bytes, which is 2 GB. Stored once per customer it takes 1,000,000 × 200 = 200 MB, ten times less.
- Updates. When a customer moves, the normalised design changes 1 row. The flat design changes the rows of all their orders: 10 for the average customer, and 5,000 for a customer with 5,000 orders.
- Consistency. The flat design has 10 chances on average, and 5,000 for the heavy customer, for one of the copies to be missed. The normalised design has one.
These are the costs that normalisation removes. What it adds is a cost on reads.
What splitting costs: the join
Section titled “What splitting costs: the join”A page that shows an order with its customer’s name, its lines and each line’s product name now needs four tables. PostgreSQL’s tutorial calls a query that accesses multiple tables at one time a join query: the database matches the key in one table with the key in another.
With the arithmetic of the last lesson, a lookup by key in a table of 10 million rows reads about 5 pages. An order with 5 lines needs 1 lookup for the order, 1 for its customer, 1 for its lines and 5 for the products: 8 lookups, so about 8 × 5 = 40 pages. One document that holds the whole order, customer name and line names included, is one lookup, 5 pages. The difference is 8 times, and it is the reason the denormalised shape exists.
Denormalising on purpose
Section titled “Denormalising on purpose”To denormalise is to store a copy of a fact where it is read, so that a read does not need the join. It is a trade: faster reads, in exchange for extra work on each write and for copies that can disagree. There are four common ways.
- Copy a column into the table that reads it. The list of recent orders carries the customer’s name, so that the list needs no join. It is right when a name that is a little old is acceptable, and when somebody owns the job of updating the copies.
- Store a derived value. A player’s total score is kept on the player and updated after each game, instead of adding up millions of game rows on every page view. The risk is that a code path forgets to update it.
- Keep a materialised view. PostgreSQL’s materialised views use the rule system like views do, but persist the results in a table-like form. They cannot be updated directly; fresh data is generated with
REFRESH MATERIALIZED VIEW. The documentation states the trade-off in one sentence: access is often much faster than reading the underlying tables, but the data is not always current. A view refreshed every night is up to 24 hours out of date. - Store the data in the shape it is read. MongoDB’s guidance is to embed related data when the application queries pieces of information together, and says that duplicating data can remove the need for joins across collections, which can improve performance. It also lists when to use references instead: when duplication is too complicated to manage, when the embedded data grows without bounds, and when the child side has high cardinality. Cassandra goes further: it has no joins, and its documentation prefers duplicating the data into a second table over joining on the client.
A cache is the same trade at another level: a copy of an answer, placed where it is read, that goes stale. The caching module is the study of how.
A different fact is not a copy
Section titled “A different fact is not a copy”Some repeated-looking values are not copies, and normalising them is a mistake. The unit price on an order line looks like the product’s price copied. It is not. It is the price that was charged on that day, a fact about the order line. If you store only a reference to the product, last year’s invoices change when the catalogue price changes. The same goes for the delivery address of a placed order, and the tax rate that applied to an invoice. The test is a question: if the original changes, should this value change too? If yes, it is a copy, and the question is how to keep it in step. If no, it is a different fact, and it belongs in the row.
Sort the values
Section titled “Sort the values”Ten values from a shop. For each, decide: one copy that others refer to, a copy placed where it is read, or a different fact that only looks like a copy. Each answer is explained.
Challenge
One copy, a copy to read, or a different fact?
Ten values from an online shop. For each one, decide whether it should be kept once and referred to, copied to where it is read, or stored as a different fact that only looks like a copy.
Sorting needs JavaScript.
Categories
- One copy, referred to by key
- Stored once, in one table. Everything else joins to it.
- A copy placed where it is read
- A deliberate duplicate that makes a read cheaper and has to be kept in step.
- A different fact
- Looks like a copy, but must not change when the original does.
Check your answers at least once before looking at the answers.
What happens if the copy and the original disagree?
Section titled “What happens if the copy and the original disagree?”A customer with 5,000 orders moves, and the shop copied the address onto every order row. The update has to change 5,000 rows. Suppose it stops half-way, because the connection drops or a timeout cuts it short. Without a transaction around all 5,000 rows, some now carry the new address and some the old one, and a report that reads orders gives one answer or the other depending on which row it reads. PostgreSQL’s transactions are all-or-nothing, which solves the half-done update but not the length of it: the update still touches 5,000 rows.
In a document store the same thing happens when the same data is embedded in many documents. An operation on one document is atomic, and changes across documents need a multi-document transaction, which MongoDB says usually costs more than single-document writes and should not replace good schema design. The honest design question for any copy is the same: who updates it, how often, how stale can it be before it matters, and how would you find out that two copies disagree?
If the answers are not clear, the normalised design is the safer one: one place, one update, and a join that costs 8 lookups instead of 1 and can be made cheap with the indexes of the last lesson. If the read cost is the problem, measure it, and then copy the smallest thing that fixes it.
- Normalisation stores each fact once and links tables by key, so a fact can only disagree with itself if the place is wrong. A foreign key stops a reference from pointing at a row that does not exist.
- A repeated fact costs space (2 GB against 200 MB for the address in the example), update work (5,000 rows against 1) and chances to miss a copy.
- Splitting costs reads: an order with 5 lines is 8 lookups, about 40 pages, against 5 for one document.
- To denormalise on purpose, copy a column, store a derived value, keep a materialised view, or store the data in the shape it is read. Each one adds write work and a way for copies to disagree.
- A value that should not change when the original changes is a different fact, not a copy: the price paid, the address a parcel was sent to, the tax rate on an invoice.
Next: how many connections an application should open to a database, and what happens when they run out.
Your progress
Built by GhaziAlibi.
© ShardCraft. All rights reserved.