Facts and dimensions

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 8:40 on Tuesday, and the first sales dashboard is live. Tess reads two numbers off it. "Average price": $5,781.75, in a shop that sells mugs and backpacks. "Stock on hand": 339 water bottles, in a warehouse that holds 101. Nothing errored. Both numbers came from SUM().

You'll learn to

  • Sort a table's columns into facts and dimensions
  • Tell which numbers you may add up, and in which direction
  • Name the three shapes of fact table and size each one
  • Count a product with several tags without counting it twice

Learn

Numbers you measure, words you group by

Start with what the dashboard is built on. Every time SwiftKart sells something, the sale produces numbers: how many units, how many dollars. Numbers you measure are called facts.

Everything that describes the sale is a dimension: who bought (the customer), what (the product), when (the date).

A quick test: dimensions are the words after "by". In "revenue by category by weekday", revenue is a fact. Category and weekday come from dimensions.

The two live in different tables. A fact table is long and narrow: millions of rows, mostly keys and numbers. A dimension table is short and wide: thousands of rows, many describing columns.

One row of fact_order_line, sorted into groups

The columns of fact_order_line in three groups: keys that point at the date, customer and product dimensions; the numbers qty, line_amount and unit_price; and order_id, line_no and status kept on the row.

Read it as one row of the table, sorted into three groups. The red box is where this lesson's first wrong number comes from.

Two columns that fit neither group

Two columns in the grey group look odd. Both are small tidy-ups with names.

order_id is something you group and count by, like a dimension. But there is no table behind it: everything about the order already lives in the other dimensions. A key with no table is a degenerate dimension.

status is a small flag. Imagine two more: channel (web, app, marketplace) and gift_wrap (true or false). Three flag columns on every row add up. So some teams build one tiny table of every combination, 5 statuses × 3 channels × 2 = 30 rows, and keep one small flags_key on the fact. That table is a junk dimension.

Sum the facts, group by a dimension

SELECT p.category,
  SUM(f.qty) AS units,
  SUM(f.line_amount) AS revenue
FROM fact_order_line f
JOIN dim_product p ON p.product_key = f.product_key
WHERE f.status <> 'cancelled'
GROUP BY p.category
ORDER BY revenue DESC;

The facts (qty, line_amount) are summed. The dimension attribute (category) is grouped by. Every analytic query has this shape: the fact table in FROM, a dimension joined on its key.

Some numbers refuse to be added

Now the first wrong number. The dashboard summed unit_price.

Some numbers add up in every direction: units, dollars. Three mugs plus two mugs is five mugs, by day, by product, by customer. These are additive facts.

Some never add up: a price, a percentage, an average. An $11.50 mug plus a $54 backpack is not a $65.50 anything. Think of two rooms at 20°C: together they are not 40°C. These are non-additive facts. Rebuild them from additive parts: average selling price is SUM(line_amount) / SUM(qty).

And some add up in one direction but not in another. They are semi-additive. The bottles are waiting for you there.

Three ways to "average" a price

SELECT
  SUM(unit_price) AS summed_price,
  ROUND(AVG(unit_price), 2) AS avg_of_line_prices,
  ROUND(SUM(line_amount) / SUM(qty), 2) AS avg_price_per_unit
FROM fact_order_line
WHERE status <> 'cancelled';

The first column is the dashboard's $5,781.75: it means nothing. The second, $33.23, gives every line the same weight, even a line of three mugs. The third, $33.53, is the real average price a unit sold for: total dollars over total units.

Remember: never sum a price, a rate or an average. Sum the parts, then divide.

339 bottles in a warehouse of 101

The second wrong number is about stock. SwiftKart counts every product on the shelf once a day and writes one row per product per day.

Stock is like a bank balance. $100 on Monday and $100 on Tuesday is not $200. Across products on one day, adding is fine: 35 mugs plus 101 bottles is 136 things on the shelf. Across days, it is nonsense.

That is a semi-additive fact: it adds up across some dimensions, but never over time. Open support tickets and account balances behave the same way. Over time, report the closing value or the average.

Before you run the query: the bottle counts were 120, 118 and 101. What will SUM say?

Stock on hand, three ways

SELECT p.name,
  SUM(s.units_on_hand) AS wrong_sum_over_days,
  ROUND(AVG(s.units_on_hand), 1) AS avg_daily_stock,
  MAX(s.units_on_hand) FILTER (WHERE s.date_key = 20250603) AS closing_stock
FROM fact_stock_daily s
JOIN dim_product p ON p.product_key = s.product_key
GROUP BY p.name
ORDER BY p.name;

fact_stock_daily (made for this card) holds one row per product per day. Summing over three days gives 339 water bottles: the dashboard's number. The closing stock is 101, and the average over the three days is 113.

The same shelf, counted on three days

Bars of water bottles on hand: 120 on 1 June, 118 on 2 June, 101 on 3 June, and a much longer bar of 339 for the sum over the three days.

The first three bars are the same shelf counted on different days. The red bar adds the three counts together, so most bottles are counted three times.

The trap: SUM never complains. SUM(unit_price) and SUM(units_on_hand) run without an error and return numbers that look plausible. Before you add up a column, ask: does adding two of these make sense? If not, rebuild it from additive parts, or take the value at the end of the period.

Three shapes of fact table

The stock table and the sales table are both fact tables, but they are built differently. Fact tables come in three shapes, named by what one row records.

  • Transaction fact: one row per event, written once and never changed. fact_order_line, payments, clicks. Most fact tables are this shape.
  • Periodic snapshot: one row per thing per period, taken on a schedule whether anything happened or not. The daily stock table. Semi-additive facts live here.
  • Accumulating snapshot: one row per run of a process with known steps, updated as each step happens. An order with placed_at, shipped_at and delivered_at.

The third is the odd one. Follow order 1048 through it.

Order 1048: three rows, or one row filled in

Order 1048 is placed, shipped and delivered: a transaction fact gains one row at each step, while an accumulating snapshot keeps one row and fills in shipped_at, delivered_at and days_to_deliver.

  1. 9 June, 16:03: placed. Both tables get their first row for order 1048. In the snapshot, the later steps are still empty.

  2. 10 June, 09:05: shipped. The transaction fact adds a second row. The snapshot adds nothing: it goes back to the same row and fills in shipped_at.

  3. 12 June, 16:03: delivered. A third row on the left. On the right, the same row is updated again, and the time between steps can now be stored too: 3 days to deliver.

Compare the two boxes at the last step: three inserts on the left, one insert and two updates on the right. In a warehouse or a lakehouse the update is the expensive operation (Lesson 5.4 shows why).

Build the snapshot: one row per order

SELECT order_id,
  MIN(at) FILTER (WHERE milestone = 'placed') AS placed_at,
  MIN(at) FILTER (WHERE milestone = 'shipped') AS shipped_at,
  MIN(at) FILTER (WHERE milestone = 'delivered') AS delivered_at
FROM order_milestones
GROUP BY order_id
ORDER BY order_id;

order_milestones has one row per step. FILTER picks out the time of each step, so the result is one row per order, with an empty column for every step that has not happened yet.

What each shape costs

Nora's rule: size a fact table before you build it. Take SwiftKart at 500,000 orders and 2 million order lines a day (round numbers for the example).

  • Transaction: rows grow with events. 2M × 365 = 730M rows a year. At about 50 bytes a row, 36.5 GB. Rows are only added, so loads are cheap.
  • Periodic snapshot: rows grow with things × periods, whether anything sold or not. 40,000 SKUs × 12 warehouses × 365 days = 175.2M rows. At 24 bytes, 4.2 GB. Snapshot hourly and it is 24 times that.
  • Accumulating: one row per order, 182.5M a year. But each is written up to four times (insert, then shipped, delivered, returned): 730M row writes.

Rows tell you storage. The write pattern tells you cost.

A year of each fact table at SwiftKart

Bars compare a year of rows: 730 million for the order-line transaction fact, 175.2 million for the daily stock snapshot, 182.5 million for the accumulating snapshot, and 730 million row writes for that snapshot.

Blue bars are rows stored; the amber bar is rows written. The accumulating snapshot stores few rows but writes as many as the transaction fact, and all but the first write of each order is an update. Adding rows is cheap everywhere. Updates on column files rewrite whole files.

One product, two tags

One request is left. Merchandising tags products and wants revenue by tag. The Canvas Tote is both eco and gift.

A tag is not one value per product, so it cannot be a column of dim_product. And a fact row cannot hold a list of keys.

The answer is a small table in the middle, with one row per (product, tag). It is called a bridge table. Joining through it turns each order line into one row per tag. That is right for "revenue by tag": the tote counts for eco and for gift. But now the tags add up to more than the shop sold.

The fix is a weight on each bridge row that sums to 1 per product: 0.5 and 0.5 for the tote.

A $22 tote through the bridge

One order line for a 22 dollar Canvas Tote is joined through a bridge table with two tag rows: revenue by tag sums to 44 dollars, then to 22 dollars again once each row is multiplied by its weight of 0.5.

  1. One order line. Order 1007 sold one Canvas Tote for $22.00. One row in the fact table, $22.00 of revenue.

  2. Join through the bridge. The tote has two bridge rows, so the line comes back twice. Each tag gets the full $22.00. That is right for each tag on its own, but the two rows add up to $44.00.

  3. Multiply by the weight. line_amount * weight gives each tag half: $11.00 and $11.00. The rows add up to $22.00 again, the same as the fact table.

Read the right-hand box at each step: its heading says what the rows add up to. Offer both numbers: the full one per tag, and the weighted one that matches total revenue.

Revenue by tag, counted and allocated

SELECT t.tag,
  SUM(f.line_amount) AS revenue_per_tag,
  ROUND(SUM(f.line_amount * b.weight), 2) AS revenue_allocated
FROM fact_order_line f
JOIN bridge_product_tag b ON b.product_key = f.product_key
JOIN dim_tag t ON t.tag_key = b.tag_key
WHERE f.status <> 'cancelled'
GROUP BY t.tag
ORDER BY t.tag;

The setup made dim_tag (eco, gift, travel) and bridge_product_tag for five products, with weights that sum to 1 for each product. revenue_per_tag counts a product once for each of its tags. revenue_allocated splits it by weight.

What the two columns add up to

tagrevenuepertagrevenueallocated
eco541.20270.60
gift1,737.101,100.60
travel2,152.001,607.90
sum of the rows4,430.302,979.10

The five tagged products sold $2,979.10. The per-tag column is right for each tag on its own, but its sum counts the tote, the bottle and the sunglasses twice. Only the allocated column adds up to what was sold.

Remember: a bridge multiplies rows. Give its weights a sum of 1 per product, and the totals add up again.

Numbers to remember

WhatThe numberWhy it matters
Transaction fact2M lines a day × 365 = 730M rows, 36.5 GB at 50 bytes a rowGrows with events; rows are only added
Periodic snapshot40,000 SKUs × 12 warehouses × 365 = 175.2M rows, 4.2 GB at 24 bytes a rowGrows with things × periods; hourly is 24 times more
Accumulating snapshot182.5M rows a year, 730M row writesUp to four writes per order; all but the first are updates
Junk dimension5 × 3 × 2 = 30 rowsIn a row store it saves real bytes on every row. In a column store a flag is a few bits after dictionary encoding, so teams use it mainly to keep BI field lists tidy
Bridge weightssum to 1 per productPer-tag revenue adds up to $4,430.30; allocated revenue to $2,979.10
Table namesfct and dim prefixesKimball's words, used in dbt projects and in the gold layer on Databricks
Semantic layerone definition per measureThe dbt Semantic Layer, Looker's LookML and Power BI measures define "average selling price" once, as a ratio of two sums, and every dashboard reuses it

What changed at SwiftKart

The dashboard gets two fixes. "Average price" becomes total dollars over total units: $33.53. "Stock on hand" becomes the closing count: 101 bottles. Tess stops reading 339.

You also labelled every number in the fact table: safe to sum, never sum, or sum across everything but time. The label goes into the model's documentation, so the next dashboard does not repeat the mistake.

You have facts and you have dimensions. Lesson 5.3 puts them together into one shape that every analyst can query the same way: the star schema.

In one line

Facts are the numbers you measure and dimensions are the words you group by; sum additive facts freely, never sum stock over time, and rebuild prices and rates from sums.

Interview corner

Give an example of a semi-additive fact and how you aggregate it.

An account balance or stock on hand. You can sum it across accounts or products on one date, but not across dates, because the same money or units would be counted every day. Over time you report the closing value of the period or the average.

What are the three types of fact table?

A transaction fact has one row per event and is never updated, like an order line. A periodic snapshot has one row per thing per period, like daily stock per product. An accumulating snapshot has one row per run of a process and is updated as each milestone happens, like an order with placed, shipped and delivered times.

A product can carry several tags. How do you report revenue by tag without double counting?

Tags are many-to-many with products, so I put a bridge table between the fact and dim_tag with one row per product and tag. Joining through it fans each line out once per tag, which is right for each tag alone but sums to more than total revenue. I add a weighting factor that sums to 1 per product, publish both revenue per tag and allocated revenue, and test that the weights sum to 1 and that allocated revenue reconciles with the fact.

You must track order fulfilment for 500,000 orders a day on a lakehouse. Accumulating snapshot or transaction fact?

The accumulating snapshot is the easiest to query (one row per order with all milestone times), but each order is written up to four times, so it means MERGE updates on 182 million rows a year, and every update rewrites the files those rows live in. I would land milestones as an append-only transaction fact (cheap, replayable) and build the accumulating snapshot from it, rebuilding only recent, still-open orders each night.