Normalise or denormalise

Part of the free LogicWiz Data Engineering course, Module 5: Data modelling. The SQL and Python run in the app, on real Postgres and real Python in the browser.

It is 3:10 p.m. Tess's new dashboard says SwiftKart took 8 orders on 1 June. The shop's database says 4. Dana, who owns that database, has a rule: never store the same fact twice. Tess wants the opposite: one wide table with everything on every row. Both turn to you.

You'll learn to

  • Explain why the app stores each fact once (3NF)
  • Build a wide table and an aggregate at a stated grain
  • Store sums and counts so an aggregate can be rolled up
  • Size a wide table against a star: bytes read, shuffles, rebuilds

Learn

Dana's rule: store each fact once

Start with Dana's side. The shop's database is built for writes: thousands of small inserts and updates a minute, each touching a row or two.

So every fact is stored in exactly one place. A product's name lives only in products. An order line stores product_id and nothing else about the product. The formal name is third normal form (3NF): every column in a table describes that table's key and nothing else.

The reward is safety. Think of a price printed on one shelf label, not written on every box. To change it you change one label, and no box can disagree.

Step through a rename, first with the name stored once, then with copies.

Rename the mug: stored once, then copied

Product 105, the Coffee Mug, and the 11 order lines that bought it: stored once, a rename changes one row; with the name copied onto every line, a rename that misses one row leaves two names for one product.

  1. Stored once. In Dana's database the name lives in one row of products. The 11 order lines that bought a mug store only product_id 105.

  2. A rename is one row. Marketing renames it Ceramic Mug. One UPDATE changes one row, and all 11 lines show the new name at once. Nothing can disagree.

  3. Now copy the name onto every line. Go back before the rename and store the name on each order line too: 11 rows. Nothing looks wrong yet.

  4. The rename misses a row. The rename must now change 11 rows in the same instant. It reaches 10. Product 105 has two names, and a report grouped by name splits the mug in two.

Read each step top to bottom: the product row, then the order lines. Copies that disagree after a change are called an update anomaly. 3NF makes it impossible, because there is only one copy.

Tess's side: big reads, few writes

Now Tess's side. A warehouse is built for reads: few writers, many readers, and queries that scan millions of rows to group them. Here joins cost time and attention. Copies are cheap, because the data changes in batches, on a schedule, through one pipeline.

So analytics does the opposite of Dana: it copies descriptive columns next to the numbers. That is called denormalising.

The star schema (Lesson 5.3) is the first step: category sits inside dim_product, not in a table of its own. The next step is a wide table, often called one big table (OBT): the fact with every dimension attribute already joined in.

Build a wide table, then ask without joins

CREATE TABLE obt_order_line AS
SELECT
  i.order_id, i.line_no,
  o.order_ts::DATE AS order_date, o.status,
  c.customer_id, c.city, c.country,
  p.product_id, p.name AS product_name, p.category,
  i.qty, i.qty * i.unit_price AS line_amount
FROM order_items i
JOIN orders o ON o.order_id = i.order_id
JOIN customers c ON c.customer_id = o.customer_id
JOIN products p ON p.product_id = i.product_id;

SELECT country, category, SUM(line_amount) AS revenue
FROM obt_order_line
WHERE status <> 'cancelled'
GROUP BY country, category
ORDER BY revenue DESC
LIMIT 5;

CREATE TABLE ... AS SELECT does the joins once. Every question afterwards reads one table. The grain did not change: 201 rows, one per order line.

Why wide is cheap in a column store

The same table stored as row-store pages and as column-store chunks; pick a query and see that the column store reads only the columns the query uses.

Pick a query and compare the bytes read on each side: the column store reads only the columns the query names. So in Snowflake, BigQuery or Parquet on Databricks, a query that uses 3 of 40 columns reads only those 3.

Normalised or denormalised?

Normalised (3NF): the appDenormalised: analytics
Each fact stored onceDescriptive columns copied onto many rows
Many small writes, kept consistentBatch writes, many large reads
Many joins to answer a questionFew joins, or none
A rename is one UPDATEA rename means rebuilding the table
Postgres or MySQL behind the appSnowflake, BigQuery or Databricks behind dashboards

A smaller copy: the aggregate table

Tess's dashboard shows revenue per day per category. It does not need 201 order lines, or 200 million. So the pipeline computes the answer once and stores it at a coarser grain: one row per day per category. That is an aggregate table.

It is fast and cheap to read, but it is a copy with limits. It answers questions at its own grain or coarser (by day, by category, by week) and never finer (by customer).

It should also store additive measures (Lesson 5.2): sums and counts of rows. Hold that thought, build the table, and then look hard at one of its columns.

One row per day per category

CREATE TABLE agg_daily_category AS
SELECT
  o.order_ts::DATE AS order_date,
  p.category,
  COUNT(DISTINCT o.order_id) AS orders,
  SUM(i.qty) AS units,
  SUM(i.qty * i.unit_price) AS revenue
FROM order_items i
JOIN orders o ON o.order_id = i.order_id
JOIN products p ON p.product_id = i.product_id
WHERE o.status <> 'cancelled'
GROUP BY o.order_ts::DATE, p.category;

SELECT category, SUM(units) AS units, SUM(revenue) AS revenue
FROM agg_daily_category
GROUP BY category
ORDER BY revenue DESC;

Rolling the aggregate up to one row per category is safe, because units and revenue are additive. Product 117 has no category, so it forms its own group with an empty category.

1 June in the aggregate table

orderdatecategoryordersunitsrevenue
2025-06-01Beauty2237.55
2025-06-01Books1358.50
2025-06-01Electronics2274.98
2025-06-01Fashion12108.00
2025-06-01Sports1118.00
2025-06-01NULL1150.00

Revenue and units add up to the day's totals. Now add up orders: 2 + 1 + 2 + 1 + 1 + 1 = 8. That is the number on Tess's dashboard.

Why 8 orders were really 4

Only 4 orders that were not cancelled were placed on 1 June. So where do 8 come from?

The orders column is COUNT(DISTINCT order_id) per category. An order that bought from Books and from Beauty is counted once under each. Add the column up, and that order is counted twice.

A count of distinct orders cannot be added across categories, because one order can buy from two. Averages fail the same way: an average of averages is wrong. When a dashboard needs distinct orders per day, give it a table with one row per day, or keep the order ids.

Remember: an aggregate table stores sums and counts of rows. Those can be added up again. Averages and distinct counts cannot.

A wide table is a copy, and copies go stale. If obt_order_line was built on Monday and a product was renamed on Tuesday, the table shows the old name until the pipeline rebuilds it. Rebuild wide and aggregate tables from the star on every run, never edit them by hand, and never re-average an average: store the sums and counts and divide at the end.

Three shapes, three jobs

So who is right, Dana or Tess? Both. Most teams end up with all three shapes, each for its job:

  • the normalised source, for the app;
  • a star schema as the warehouse's single source of truth, with history, conformed dimensions (Lesson 5.3) and one place to fix a definition;
  • wide and aggregate tables built from the star, for the busiest dashboards and for machine learning features.

The wide and aggregate tables are disposable. When a definition changes, you fix it once in the star and rebuild them in minutes.

Which table is built from which

A graph in three columns: the normalised source tables feed the star schema, and the star feeds a wide table and an aggregate table that dashboards read.

Read it left to right. Grey belongs to the app. Blue is the star, where history and definitions live. Amber tables are copies: rebuilt from the star on every run and safe to throw away.

Why the wide table reads fewer bytes

Should a busy dashboard read the star or the wide table? Size one query, "June revenue by country and category", at real scale: 60M fact rows for June, 20M customers, 50,000 products.

A column store reads only the columns a query names. So count columns:

  • The star reads three fact columns (two keys and the amount), then the key and country of all 20M customers, and joins them.
  • The wide table reads country, category and line_amount, and joins nothing.

The join is the expensive part. Spark can copy a small table to every worker and join on the spot (a broadcast), but only up to 10 MB by default. A bigger table means sorting both sides and moving them across the network first. That move is called a shuffle (Module 12).

The sum, column by column

What the query readsSumMB
Star: customerkey, productkey, lineamount60M rows × (8 + 4 + 8) bytes1,200
Star: dimcustomer key and country20M rows × (8 + 1) bytes180
Star: dimproduct50,000 rowswell under 1
Star, in totalthen a join that shufflesabout 1,380
Wide: country60M rows × 1 byte60
Wide: category60M rows × 6 bits45
Wide: lineamount60M rows × 8 bytes480
Wide table, in totalno join at all585

These are encoded widths: country has 200 values, so 1 byte is enough, and category has 50, so 6 bits. A column with few distinct values is almost free to copy. That is exactly why the wide table works.

June revenue by country and category

Bars compare one dashboard query: the star reads 1,200 MB of fact columns and 180 MB of dim_customer and then shuffles about 1,380 MB for the join, while the wide table reads 585 MB and shuffles nothing.

The 180 MB of dim_customer is far over the 10 MB limit, so Spark uses a sort-merge join and shuffles the fact too. The wide table reads less than half the bytes and skips the shuffle. Sizes are before run-length encoding and compression.

What the wide table pays instead

The wide table moves the join from every query to the build. The build is where the bill arrives:

  • Rebuilds. A year of the wide table is 730M rows. Rebuilt nightly at about 40 bytes a row, that is 29 GB written every night. The star appends 2M fact rows.
  • Changes fan out. A customer who moves country is one dimension row in the star, but every one of their lines in the wide table, spread over every file (Lesson 5.4).
  • History is frozen at build time: "as it was" or "as it is", not both.
  • Nearly unique columns cost real bytes. customer_email is about 25 bytes and almost never repeats, so it does not shrink. The bars below show the price.

One column, customer_email, stored two ways

Bars compare the raw size of the customer_email column: 0.5 GB on the 20 million rows of dim_customer against 18.25 GB copied onto 730 million rows of the wide table.

Dictionary encoding only helps when values repeat. A nearly unique column is stored plain, once per row. Columns nobody reads cost no scan time, but they are still written, stored and rebuilt every night.

Star or wide table: the trade, with numbers

Star schemaWide table
Bytes for the June queryabout 1,380 MB, plus a shuffle585 MB, no join
A customer changes countryupdate 1 dimension rowrewrite every row of that customer
As it was and as it isboth, by the join you pickone, frozen at build time
Add customeremail20M values, about 0.5 GB730M copies, about 18 GB
Nightly write2M fact rows + dimension changesabout 29 GB if fully rebuilt
Best forthe governed core, any questionone busy dashboard, ML features

The usual answer is both: the star as the source of truth, and a wide or aggregate table per heavy use case, rebuilt from the star and safe to throw away.

Numbers to remember

ThingValueWhat it means
spark.sql.autoBroadcastJoinThreshold10 MB by defaultabove it, Spark shuffles both sides of the join (a sort-merge join)
Delta min/max statisticsfirst 32 columns by defaulta 120-column wide table skips nothing on the rest, unless you reorder or set delta.dataSkippingStatsColumns
A year of the wide table730M rows × about 40 bytesabout 29 GB written by every full nightly rebuild
Clustering the wide tableby country and categoryshrinks those two columns to almost nothing
BigQuerynested and repeated fieldsan order row holds an array of its lines, so no join is needed at all
Power BIprefers a star schemait does its own joins
dbtmakes rebuilding cheapa wide model is one SELECT with joins over the star

Snowflake and Databricks teams often publish one wide table per busy dashboard, and keep the star behind it.

What changed at SwiftKart

The meeting ends without a winner, because there is none. Dana keeps her normalised database. The star stays the source of truth. Tess gets obt_order_line and agg_daily_category, both rebuilt from the star on every run.

And the 8 is gone. Her dashboard no longer adds up a distinct count: the order count comes from a table with one row per day, where 1 June says 4.

Next, Lesson 5.6: the warehouse now holds raw copies, cleaned tables, a star and these copies for dashboards. Which table is built from which, and what is each one allowed to contain? That is what layers are for.

In one line

Store each fact once where many small writes must stay consistent; copy it into stars, wide tables and aggregates where big reads need speed, and keep sums and counts in the copies so they can be added up again.

Interview corner

When would you normalise and when would you denormalise?

Normalise an OLTP database, where many small writes must stay consistent and each fact should live in one place. Denormalise for analytics, where reads dominate and joins over large tables cost time. In a warehouse I keep a star schema as the governed core and build wide or aggregate tables from it for the busiest use cases.

What is one big table (OBT) and what are its downsides?

A single wide table with the fact and all its dimension attributes pre-joined, so queries need no joins. It is fast to query in a column store and easy for analysts. The downsides are duplicated data that can go stale, rebuild cost when a dimension changes, and no clean way to keep dimension history unless you build it from a star.

What should an aggregate table store?

Additive measures at a stated grain: sums and row counts, so it can be rolled up correctly to coarser grains. Averages and distinct counts should be computed at query time from the sums, or kept in a separate table at the grain where they are needed.

40 dashboards read a 2-billion-row fact on BigQuery or Databricks. Would you serve them from the star or from wide tables?

I keep the star as the governed source and size the heavy queries. Copying low-cardinality attributes costs a few bits a row after dictionary encoding, while a join to a large dimension (tens of millions of customers) forces a shuffle of the fact on every query, so the five or six busiest dashboards get a wide or aggregate table clustered by their filters. The rest query the star. I keep high-cardinality text such as emails out of the wide tables, rebuild them from the star on a schedule, and test that their totals reconcile with the fact.