How should I structure data so that reports are right and fast? Grain, keys, facts and dimensions
TL;DR
Difficulty: Intermediate
The shop database is built for taking orders, not for answering questions, so the same report gives different totals depending on who writes the query.
- Declare the grain first: one sentence saying what one row means, with a unique key and a test.
- Store additive facts and compute ratios such as average order value only after summing.
- Allocate order level amounts like shipping to lines with a rule that keeps every penny, or keep them at order grain.
- Flatten dimensions, give each row a surrogate key and every gap an Unknown row, one category per product.
- Pick the fact table type that fits: transaction, periodic snapshot or accumulating snapshot.
- Decide the reporting time zone in writing and keep the UTC timestamp too.
Ask the shop database how much each category sold last month and it may well answer with a total bigger than the whole month's takings. Nothing is broken. The data is simply in the wrong shape for the question. This chapter shows how to reshape it once, in tested code, so that the right answer is also the easy one.
Two answers to one question, and neither is right
Priya runs Wrenfield Home, an online homeware shop in Leeds. On a Monday morning she asks Callum, her developer and data engineer, a simple question: how much did each category sell in June? Callum writes a query against the shop database, joins orders to line items, line items to variants, variants to products, products to categories, adds it up and sends her a table. Kitchen £41,200, Living £36,900, Bedroom £28,400, Bathroom £17,340, Gifts £36,630. Total £160,470.
Priya frowns. The finance report says the shop took £142,560 in June, shipping and VAT included. How can the categories add up to more than everything?
Nothing in the query was wrong in the sense of a syntax error. The database answered exactly what it was asked. The trouble is that the shop database was never built to answer that question, and the join quietly counted some sales twice. This chapter is about the fix that lasts: structuring the data so that the right answer is the easy answer. That structure has a name, a dimensional model, and its central idea fits in one word: grain.
By the end you will be able to declare the grain of any table in one sentence, tell facts from dimensions, choose between natural and surrogate keys, pick the right kind of fact table, build a date dimension that respects your time zone, and write the dbt models that turn Solidus tables into a star schema that reports can trust. If you have not yet read the chapter on data types, schemas and formats, it is worth doing first, because every column below relies on the type choices made there.
Example: where the extra £25,830 came from
Wrenfield Home sells about 1,400 products. Some of them sit in two categories at once: a set of ceramic mugs is in Kitchen and also in Gifts, because that is how customers browse. In Solidus, categories are taxons, and a product can belong to many taxons through the table spree_products_taxons.
When Callum joined line items to products and products to taxons, every line for a mug set turned into two rows, one per taxon. In June, lines for products in two categories were worth £25,830. Each of those pounds was counted once under Kitchen (or Living, or Bedroom) and once more under Gifts.
- True item revenue in June: £134,640.
- Double counted: £25,830.
- What the query reported: £134,640 + £25,830 = £160,470.
The extra £25,830 is not a bug in SQL. It is a mismatch between the question (one row per sale, one category per sale) and the shape of the data (one sale can belong to many categories). The rest of this chapter is about removing that mismatch by design.
Why the shop database has the wrong shape for reporting
The database behind a Solidus shop is an online transaction processing (OLTP) database. Its job is to take thousands of small writes safely: add this item to a basket, take this payment, decrement this stock count. To do that well it is normalised.
Normalisation comes from Edgar Codd's relational model of 19701. The practical rule of thumb for the common level, third normal form (3NF), was put memorably by William Kent in 1983: every non key field must provide a fact about the key, the whole key, and nothing but the key2. In plain words: store each fact once, in the one table it belongs to, and point to it from everywhere else.
That is exactly right for writing. If a product name changes, you change it in one row of spree_products and every order, basket and page sees the new name. Nothing can drift out of step, because nothing is stored twice.
It is exactly wrong for reading at scale. A question like "revenue by category, by customer region, by month" has to rebuild the picture from many small tables at query time. Every join is a place where rows can multiply (the mug sets), vanish (an inner join to a missing address) or be misread (a status column whose values changed in a release). The query is long, slow on large data, and a different person writing it will make different choices and get a different number.
A dimensional model turns this around. It stores data in the shape of the questions: one table of measurements (facts) surrounded by a few wide, flat tables of descriptions (dimensions). Ralph Kimball and Margy Ross set out the method in The Data Warehouse Toolkit, third edition, 2013, still the standard reference3. Their two stated goals are simplicity and speed4, and both matter to a small shop: simplicity, because Priya should be able to drag "category" and "month" into a pivot table without knowing what a taxon is, and speed, because nobody waits for a seven table join every time a dashboard refreshes.
Example: the seven tables behind one question
To answer "revenue by category, by customer region, by month" straight from Solidus, Callum needs at least these tables (the column names below are checked against the Solidus schema5):
| Table | What it holds | Why the question needs it |
|---|---|---|
spree_orders | one row per order: number, state, completed_at, ship_address_id, shipment_total | which orders count, and when |
spree_line_items | one row per product line: order_id, variant_id, quantity, price, promo_total, included_tax_total | the money |
spree_variants | one row per sellable item: sku, product_id, cost_price | link a line to a product |
spree_products | one row per product: name, slug, deleted_at | the product |
spree_products_taxons | one row per product and taxon pair | link a product to categories |
spree_taxons | one row per category node: name, parent_id | the category name |
spree_addresses and spree_countries | the shipping address and its country | the region |
That is seven joins, two of them able to multiply rows (spree_products_taxons, and any join to payments or shipments), and one able to drop rows (orders without a shipping address, such as gift cards sent by email). Every analyst who writes this query from scratch has seven chances to differ. The dimensional model makes those choices once, in code, under test.
Grain: the decision that comes before every other
Kimball's design method has four steps, in this order: select the business process, declare the grain, identify the dimensions, identify the facts6. The second step is the one people skip, and it is the one that decides whether numbers come out right.
The grain says exactly what one row of a table represents. Kimball calls declaring it "the pivotal step" and a "binding contract on the design", and adds that different grains must not be mixed in the same fact table7. Write it as one plain sentence that a shop owner could check: "one row per line item on a completed order", never "order data".
Three rules follow from it.
- Declare the grain before choosing columns. A column either belongs at that grain or it does not. Shipping cost belongs to an order, not to a line, so it cannot sit on a line table as it is. It has to be allocated first (more on that below).
- Prefer the atomic grain. The atomic grain is the lowest level at which the business records the event: the order line, not the order, and not the day. Kimball's advice is to start there because it survives questions nobody has asked yet7. You can always add up order lines to days. You can never split a day back into lines.
- Test the grain. A grain sentence implies a unique key. "One row per line item" means
line_item_idis unique. If a test finds two rows with the sameline_item_id, the grain is broken and every sum above it is suspect.
Example: the grain statements for Wrenfield Home
Callum writes the grain of every table in the model before he writes a line of SQL. This table lives in the project's documentation and every model's description repeats its line.
| Table | Grain, in one sentence | Unique key | Rows over five years (estimate) |
|---|---|---|---|
fct_order_lines | one row per line item on a completed order | line_item_id | about 273,000 |
fct_orders | one row per completed order | order_number | about 118,800 |
fct_sessions | one row per GA4 session | user_pseudo_id plus ga_session_id | about 4 million (three years of export) |
fct_stock_daily | one row per variant per stock location per day | variant_id, stock_location_id, snapshot_date | about 3.8 million |
fct_order_fulfilment | one row per completed order, updated as it moves on | order_number | about 118,800 |
dim_customer | one row per customer (account or guest email) | customer_key | about 78,000 |
dim_product | one row per variant, the item a customer actually buys | product_key | about 2,300 including discontinued |
dim_date | one row per calendar day, plus one Unknown row | date_key | about 4,000 |
The row estimates come straight from the business baseline. Orders: 1,980 a month is 23,760 a year, or 118,800 over five years. Lines: Callum measured an average of 2.3 lines per order in the shop (an invented figure for this example), so
where is orders per year, is the average number of lines per order and is the years of history. Customers: about 1,300 new customers a month is 15,600 a year, or 78,000 over five years. Sessions: 110,000 a month over the three years the GA4 export has been running is 3.96 million.
None of these is large for a modern warehouse. That matters later, in the section on one big table.
Facts: what you measure, and whether you may add it up
Facts are the numbers a business process produces: quantity, revenue, discount, cost, shipping. They live in fact tables, at the declared grain. Kimball sorts them into three kinds by how they behave when you add them up8.
- Additive facts can be summed across every dimension. Line revenue is additive: you can add it across products, days, customers and categories and the total means something.
- Semi additive facts can be summed across some dimensions but not time. Stock on hand is the classic case: the stock of all products on one day adds up to the total stock that day, but adding Monday's stock to Tuesday's gives a number that means nothing.
- Non additive facts cannot be summed at all. Ratios are non additive: conversion rate, margin percentage, average order value.
The practical rule that comes with this is the one most dashboards break: store the additive parts, never the ratio, and compute the ratio after summing8.
Example: the average order value that was £4.50 wrong
Average order value (AOV) is revenue divided by orders. See Foundations: ratios and rates and Foundations: mean if it has been a while.
where is the average order value, is the revenue of order , and is the number of orders in the period.
Suppose a weekly summary table stored AOV as a column. Week A had 400 orders worth £30,000, an AOV of £75.00. Week B had 100 orders worth £6,000, an AOV of £60.00. Priya's spreadsheet averages the two stored values:
Here and are the two stored weekly AOVs and is the number of weeks, so the spreadsheet says £67.50. The true AOV over both weeks sums the parts first:
Here and are the weekly revenues and and the weekly order counts. The real figure is £72.00, so the shortcut was £4.50 too low, because it gave the quiet week as much weight as the busy one. The fix is structural, not a reminder to be careful: the fact table stores revenue and order_count, both additive, and the AOV is only ever computed from their sums. Chapter six of this series, on SQL traps, goes through averages of averages and their relatives in detail.
When a fact lives at the wrong grain: allocation
Some numbers in a shop are recorded at the order level, not the line level. Shipping is charged once per order (spree_orders.shipment_total, the sum of spree_shipments.cost). An order level adjustment, if your promotions create one, sits on the order too. Kimball calls these facts of differing granularity and gives a clear instruction: allocate the header facts down to the line level using a rule the business agrees to, so they can be sliced by every dimension9.
There are only two honest options. Keep shipping in a separate order grain table (fct_orders) and never put it on the lines, or allocate it to the lines with a written rule. What you must never do is copy the order's full shipping onto each of its lines. A three line order would then report its shipping three times.
The usual rule is proportional allocation: each line gets a share of the order amount in proportion to its share of the item value. See Foundations: ratios and rates.
where is the shipping allocated to line , is the order's total shipping, is the item value of line after discounts, and is the number of lines on the order.
There is a catch nobody mentions until finance spots it: rounding. Shares come out as fractions of a penny, and if you round each line on its own, the pennies no longer add up to the order. Across 23,760 orders a year those pennies drift into a reconciliation gap that someone will have to explain. The robust method works in whole pence and hands out the leftover pennies one at a time to the lines with the largest remainders, a technique known as the largest remainder method.
Example: allocating £3.95 shipping across three lines
Order R482913577 has three lines: a vase at £36.00, two cushion covers at £14.00 each (£28.00), and a candle at £9.99. Items total £73.99. Shipping is £3.95.
Step 1, the exact shares:
where is the vase's exact share, is the shipping, the vase line and the items total.
where is the cushion covers' exact share and their line value.
where each is the exact allocated shipping in pounds before rounding.
Step 2, rounding each line on its own gives £1.92, £1.49 and £0.53. Their sum:
The rounded shares add up to , not . One penny has gone missing.
Step 3, the largest remainder method. Work in pence: 395 pence to share. Round every share down: 192, 149 and 53 pence, which adds up to 394. One penny is left over. The remainders after rounding down are 0.19 pence for the vase, 0.48 for the covers and 0.33 for the candle. The covers have the largest remainder, so they get the spare penny.
Result: vase £1.92, covers £1.50, candle £0.53. Sum: £3.95, exactly the order's shipping. The rule is deterministic (ties are broken by line number), so a rerun always gives the same pennies.
The same idea applies to order level discounts and to payment fees if you ever want them on lines. Write the rule down once, test it once, and use it everywhere. If you want to see where allocated shipping and fees go next, the article on unit economics and contribution margin per order builds on exactly these line level numbers.
Dimensions: the words you group and filter by
If facts are the numbers, dimensions are the context: who bought, what, when, where, through which channel. They are the columns that end up in a report's rows and filters. A dimension table has one row per thing (one customer, one product, one day) and as many descriptive columns as are useful.
Three design rules make dimensions pleasant to use.
- Flatten the hierarchies. The operational instinct is to keep category in its own table and point at it. In a dimension, resist that: Kimball recommends denormalising fixed hierarchies into plain columns on one flat row, for simplicity and speed4.
dim_productsimply hascategory_name,parent_category_name,product_name,sku,brandside by side. - One value per row and grain. Each fact row must point at exactly one row in each dimension. If a product can really belong to several categories, either choose one (a primary category) or, when you truly need all of them, put a bridge table between the product and its categories with a weight per pair, so that the shares add up to one. Kimball describes these bridge tables for genuinely multivalued dimensions10. The mug sets from the opening example were a multivalued dimension treated as a single valued one.
- No nulls in descriptive columns. Replace a missing value with a readable label such as "Unknown" or "Not applicable". Different tools group and filter nulls differently, so a null category can silently disappear from one chart and appear in another11.
Example: one category per product, from the primary taxon
Recent Solidus versions add a primary_taxon_id column to spree_products, a foreign key to spree_taxons12. That is exactly the single valued category the model needs. Where a shop runs an older version, Callum keeps a small, reviewed mapping file instead (a dbt seed with product_id and primary_category), which Priya can edit.
dim_product then carries one category_name per row, taken from the primary taxon, with "Unknown" for products that have none. The June report becomes a plain group by on category_name, and it adds up:
| Category | June item revenue |
|---|---|
| Kitchen | £41,200 |
| Living | £36,900 |
| Bedroom | £28,400 |
| Bathroom | £17,340 |
| Gifts | £10,800 |
| Total | £134,640 |
The browsing view (mugs appear under Gifts on the website) stays in the shop, where it belongs. Should Priya ever want "everything that appears under Gifts on the site", that is a different question, answered through the bridge table with a clear label, never mixed into the revenue by category report.
Natural keys and surrogate keys
Every table needs a key, the column or columns that identify a row. There are two families.
A natural key comes from the business or the source system: the order number R482913577, the stock keeping unit (SKU) WHVASE036 printed on a label, a customer's email address. Natural keys are meaningful, and that is their weakness. They change (a customer changes email), they get reused (a discontinued SKU code is given to a new product), they clash between systems (the warehouse uses its own SKU format with a prefix), and some of them are personal data.
A surrogate key is a value created by the warehouse with no meaning at all, used only to join. Kimball's rule is firm: dimension primary keys should be surrogate keys the warehouse controls, because a natural key cannot stay unique once you keep history and because several sources may bring incompatible natural keys13. Kimball also separates the surrogate key of one version of a row from the durable key of the real thing, which never changes even when the row is versioned14. That distinction matters in the chapter on history.
Integers or hashes
Kimball's original surrogate keys are integers handed out in sequence, 1, 2, 313. In dbt projects you will more often see hashed keys, built with the generate_surrogate_key macro from the dbt_utils package: it casts each input column to text, replaces nulls with a fixed marker, joins them and hashes the result15. On BigQuery the hash is an MD5 digest written out as 32 hexadecimal characters.
Hashed keys have one big practical advantage: they are deterministic. The fact model can compute product_key from variant_id by itself, without looking it up in dim_product, so facts and dimensions can be built in parallel and rebuilt from scratch at any time and the keys come out identical. Sequence integers depend on load order, so a full rebuild can hand out different numbers and break every saved link.
The price is size (a 32 character string instead of a small integer) and a theoretical chance that two different inputs produce the same hash, a collision. How theoretical? For keys spread over a hash of bits, the birthday approximation gives the chance of at least one collision. See Foundations: probability.
where is the probability that any two keys collide, is the number of keys, and is the hash length in bits ( for MD5).
Example: how likely a clash is for Wrenfield Home's order lines
Five years of order lines give . With MD5, , so
See Foundations: probability for the birthday problem behind it. Here is squared and is . That is a probability with 27 zeros after the decimal point. Collisions are not the risk worth worrying about. The real risks with hashed keys are human: hashing a natural key that is itself dirty (an email with a trailing space hashes differently from the same email without it) and changing the list of input columns, which changes every key at once. So the inputs are cleaned before hashing, and the list of columns is part of the model's tested contract.
Example: the customer key and the 3.1% duplicates
Wrenfield Home knows that 3.1% of its customer accounts are duplicates: the same person with an email differing in case or whitespace, or a guest checkout next to a real account. If dim_customer used the raw email as its key, "Priya.Shah@example.com " and "priya.shah@example.com" would be two customers, lifetime value would be split, and the repeat purchase rate would look worse than it is.
For now, Callum builds a natural identifier that is at least consistent: user: plus the Solidus user_id for account holders, and guest: plus the lowercased, trimmed email for guest orders. The surrogate customer_key is the hash of that identifier. This does not merge a guest checkout with the account of the same person. That is entity resolution, and chapter eleven of this series is devoted to it. What the model does now is make room for it: because every fact row points at customer_key, the day entity resolution starts mapping several identifiers to one durable customer, only dim_customer and its mapping change. The fact tables do not.
Three kinds of fact table
Kimball distinguishes three kinds of fact table, and nearly every measurement a shop takes fits one of them161718.
- Transaction fact table. One row per event at a moment in time: a sale, a refund, a page view. Rows are inserted and, in principle, never changed.
fct_order_linesis one. - Periodic snapshot. One row per thing per period, describing its state: stock per variant per day, open baskets per day, newsletter list size per week. The grain is the period, and a row exists even when nothing happened, with zeros or nulls17. Its main facts are usually semi additive.
- Accumulating snapshot. One row per instance of a process with clear steps, updated as the instance moves on: an order from completion to dispatch, return and refund. It has one date per milestone, and it is the only kind of fact table whose rows are deliberately updated18.
Example: stock on hand, and why you must not sum it over days
Solidus keeps the current stock of every variant at every stock location in spree_stock_items.count_on_hand5. That column is overwritten on every sale, so the shop database only ever knows today. To answer "how did stock of the oak serving board develop last week?", Callum takes a copy every night into fct_stock_daily, one row per variant per location per day.
For the oak serving board the snapshot shows 40 on Monday, 37 on Tuesday and 35 on Wednesday. Summing over the three days gives
where , and are the daily counts. The result, , is meaningless: the shop never had 112 boards. Across days, the right aggregations are the closing value (35), the average level, or the minimum. The average level is
where is the average stock on hand over the three days. See Foundations: mean. Across products on one day, summing is fine: the boards plus every other product on Wednesday is Wednesday's total stock. That is what semi additive means in practice, and it is why the column description in the model says, in words, "do not sum across dates".
Example: one order's journey as an accumulating snapshot
Order R482913577 was completed on Monday 1 June 2026. It was dispatched on 2 June. The customer returned the candle, and the warehouse received it on 9 June. Because the 3PL (third party logistics) warehouse file arrives up to five days late for returns, the return only reached the warehouse data on 14 June. The refund went out on 11 June.
fct_order_fulfilment has one row for this order, first inserted on 1 June and updated four times. Its milestone columns are completed_date_key, shipped_date_key, return_received_date_key and refunded_date_key, each pointing at dim_date, with the Unknown date row until the milestone happens.
Kimball suggests storing each lag measured from the start of the process, so any lag between two steps is a simple subtraction19. For this order:
- days to dispatch: 1
- days to return received: 8
- days to refund: 10
Days from return received to refund:
where is the lag to refund and the lag to return received, both counted from completion. So the refund took two days after the parcel arrived. Averaged over all returned orders, that number becomes a service measure Priya can actually manage. The row also shows why the 3PL delay matters for modelling: the return milestone is filled five days after the event it records, so a fulfilment report for last week is not final until five days later. A later chapter on business rules deals with late data and restating closed periods.
The order number as a degenerate dimension
Some identifiers are neither facts nor worth a dimension table of their own. The order number is the standard case. Once every order level attribute (customer, date, shipping country) has been copied onto the line, there is nothing left to describe in an "order dimension" except the number itself. Kimball's answer is to keep the number on the fact table as a degenerate dimension, a dimension key with no dimension table behind it20. Kimball also notes that in header and line structures, all the header's dimension keys belong on the line fact table21.
Example: finding every line of one order
When a customer rings about order R482913577, Priya's colleague filters fct_order_lines on order_number = 'R482913577' and sees all three lines with their allocated shipping. Counting distinct order numbers in a month gives the order count without a separate table:
| Measure | June value |
|---|---|
Distinct order_number values | 1,980 |
| Lines | 4,554 |
| Lines per order | 2.3 |
The line count follows from the average: . Keep in mind that counting distinct values is not additive: the distinct orders of June and July cannot be added if an order could appear in both, which is why fct_orders at order grain exists alongside the line table.
The date dimension, and the time zone question
Every fact table has at least one date, and nearly every report groups by week, month or quarter. Kimball's calendar date dimension puts all of that into one table with one row per day: day of week, ISO week, month name, quarter, financial period, holiday flag. You would never want to compute Easter in SQL, as Kimball puts it, you look it up22. Unusually, the date dimension may use a meaningful key such as the integer 20260601, but it still needs a special row for unknown dates, and filters should use its columns, not arithmetic on the key22.
A fact table can have several dates (ordered, dispatched, refunded). Each one is a role played by the same date dimension: order_date_key, shipped_date_key, refunded_date_key. Kimball calls this a role playing dimension and recommends a separately named view for each role, so that the references stay independent23.
Then comes the decision that trips up almost every shop: which day does an order belong to? Solidus stores completed_at as a timestamp in Coordinated Universal Time (UTC). Priya thinks in UK time. In summer the UK runs on British Summer Time (BST), one hour ahead of UTC. Kimball's guidance for several time zones is to keep both: the UTC timestamp and a local date, each with its own date key24.
Example: the order that belonged to two months
An order is completed at 11.30pm UTC on 30 June 2026. In Leeds, it is 12.30am on 1 July.
- Grouped by UTC date: June.
- Grouped by UK date: July.
Neither is wrong, but they cannot be mixed. Callum writes the rule down: management reporting uses the shop's local date, Europe/London, so the trading day matches what Priya sees on the shop's own screens and what the bank sees in its daily settlement. The UTC timestamp stays on the fact row as completed_at_utc for reconciliation with GA4, whose event_timestamp is recorded in microseconds UTC25.
How much does this move? On a typical night only a handful of orders fall in the hour between 11pm and midnight UTC, but at a month boundary every one of them changes month. If Wrenfield Home takes eight orders in that hour on the last night of June, then June loses eight orders and July gains them, about £576 at an AOV of £72:
where is the number of orders in that hour and the AOV in pounds. Small, and exactly the size of difference that makes finance stop trusting a dashboard.
Example: building dim_date in BigQuery and PostgreSQL
The UK government publishes bank holidays for England and Wales, Scotland and Northern Ireland as a JSON feed26. Callum turns the England and Wales part into a dbt seed once a year:
# scripts/refresh_bank_holidays.py
# Writes the England and Wales bank holidays from the GOV.UK feed into a dbt seed.
import csv
import json
import urllib.request
URL = "https://www.gov.uk/bank-holidays.json"
with urllib.request.urlopen(URL) as response:
data = json.load(response)
with open("seeds/uk_bank_holidays.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["holiday_date", "holiday_name"])
for event in data["england-and-wales"]["events"]:
writer.writerow([event["date"], event["title"]])
The date dimension itself, in BigQuery's dialect, uses GENERATE_DATE_ARRAY to produce one row per day27 and the date functions for ISO weeks28. Here is the model:
-- models/marts/dim_date.sql (BigQuery dialect)
-- Grain: one row per calendar day, plus one Unknown row.
with days as (
select day as date_day
from unnest(generate_date_array('2021-01-01', '2031-12-31')) as day
),
holidays as (
select cast(holiday_date as date) as holiday_date, holiday_name
from {{ ref('uk_bank_holidays') }}
)
select
cast(format_date('%Y%m%d', d.date_day) as int64) as date_key,
d.date_day,
extract(year from d.date_day) as calendar_year,
extract(quarter from d.date_day) as calendar_quarter,
extract(month from d.date_day) as month_number,
format_date('%B', d.date_day) as month_name,
format_date('%Y-%m', d.date_day) as year_month,
extract(isoyear from d.date_day) as iso_year,
extract(isoweek from d.date_day) as iso_week,
format_date('%A', d.date_day) as day_name,
extract(dayofweek from d.date_day) in (1, 7) as is_weekend, -- 1 = Sunday, 7 = Saturday
h.holiday_date is not null as is_bank_holiday,
coalesce(h.holiday_name, 'Not a bank holiday') as holiday_name
from days as d
left join holidays as h
on h.holiday_date = d.date_day
union all
-- The Unknown row: facts whose date is not known yet point here, never at null.
select
-1, cast(null as date), null, null, null, 'Unknown', 'Unknown',
null, null, 'Unknown', false, false, 'Unknown'
A shop that keeps everything in PostgreSQL alone can build the same table with generate_series29. In PostgreSQL, extract(week ...) already returns the ISO 8601 week, and isodow numbers Monday as 1 and Sunday as 7:
-- PostgreSQL dialect
create table analytics.dim_date as
select
to_char(d, 'YYYYMMDD')::int as date_key,
d::date as date_day,
extract(year from d)::int as calendar_year,
extract(isoyear from d)::int as iso_year,
extract(week from d)::int as iso_week,
to_char(d, 'FMMonth') as month_name,
extract(isodow from d) in (6, 7) as is_weekend
from generate_series(date '2021-01-01', date '2031-12-31', interval '1 day') as g(d);
Result for the first days of the June example:
| date_key | date_day | iso_week | day_name | is_bank_holiday |
|---|---|---|---|---|
| 20260601 | 2026-06-01 | 23 | Monday | false |
| 20260602 | 2026-06-02 | 23 | Tuesday | false |
| 20260603 | 2026-06-03 | 23 | Wednesday | false |
Ten years of days is about 4,000 rows. It costs nothing to store and saves every analyst from writing their own week logic.
Star schema or snowflake
Put a fact table in the middle and its dimensions around it, each joined by one key, and the diagram looks like a star. That is the star schema. If you normalise the dimensions again (product points to category, category points to department), the diagram branches out and is called a snowflake.
Kimball's advice is to avoid snowflakes: a flattened dimension holds exactly the same information, is easier for people to understand and navigate, and snowflakes can hurt query performance30. In a columnar warehouse, a repeated category name on 2,300 product rows costs next to nothing in storage, and it saves a join on every query.
There is one fair exception. A shared lookup that several dimensions use and that changes on its own schedule (a country table with ISO codes, VAT rates and region names) can stay as a separate small table that the build joins in. Kimball calls that an outrigger31. The test is simple: the analyst using the model should still see one flat dimension.
Example: the June report against the star
With the star in place, Priya's question is one join per dimension and no join that can multiply rows, because each fact row points at exactly one product row and one date row:
-- BigQuery dialect
select
p.category_name,
sum(f.line_amount_incl_vat) as item_revenue
from {{ ref('fct_order_lines') }} as f
join {{ ref('dim_product') }} as p on p.product_key = f.product_key
join {{ ref('dim_date') }} as d on d.date_key = f.order_date_key
where d.year_month = '2026-06'
and not f.is_canceled
group by p.category_name
order by item_revenue desc
It returns the five categories that add up to £134,640, and the bridge from there to finance's figure is now explicit rather than mysterious:
Shipping here is the average of £4 per order times 1,980 orders. The VAT step divides by 1.2, because UK prices include VAT at 20%:
where is the order total in pounds including VAT and is one plus the VAT rate. Every step in that bridge is a column or a rule in the model, so the same bridge comes out every month.
Conformed dimensions: how different facts meet
A shop has many business processes: orders, returns, sessions, ad spend, stock. Each gets its own fact table at its own grain. The power of the dimensional model comes from the dimensions they share. Kimball calls a dimension conformed when it means the same thing, with the same column names and values, wherever it is used, and it is what lets results from separate fact tables line up on the same rows of a report, a technique called drilling across32. Kimball's planning tool for this is the bus matrix: business processes as rows, dimensions as columns, a tick where they meet33.
Example: the bus matrix for Wrenfield Home
| Business process (fact table) | dim_date | dim_product | dim_customer | dim_channel | dim_location |
|---|---|---|---|---|---|
Orders (fct_order_lines) | yes | yes | yes | yes | yes |
Returns (fct_return_lines) | yes | yes | yes | yes | yes |
Stock (fct_stock_daily) | yes | yes | no | no | yes |
Web sessions (fct_sessions) | yes | no | no | yes | no |
Ad spend (fct_ad_spend_daily) | yes | no | no | yes | no |
dim_channel is the conformed one that makes marketing reports possible. It has one row per channel with the same names everywhere ("Paid search", "Paid social", "Email", "Organic search", "Direct"), and both the GA4 sessions and the Google Ads and Meta Ads cost rows are mapped to it.
Example: drilling across to a marketing efficiency ratio
Priya wants June's marketing efficiency ratio (MER): revenue for every pound of ad spend. The trap is to join fct_order_lines to fct_ad_spend_daily on date. Each order line would meet every spend row of its day, and both sums would multiply. Drilling across does it in two steps: sum each fact table on its own to the shared grain (here, the month in dim_date), then join the two small results. See Foundations: ratios and rates.
where is the marketing efficiency ratio, is net revenue excluding VAT in the period, and is total ad spend on Google and Meta in the same period.
For June:
where is June's net revenue and June's ad spend, both in pounds. So every pound of advertising went with £8.49 of net revenue. The figure only means something because both sides use the same dim_date (the same month boundaries, in UK time) and the same definition of revenue. The eCommerce metrics glossary explains how MER differs from return on ad spend, and the KPI tree shows where it sits among the levers.
Sessions from GA4: a second fact table with its own grain
The GA4 (Google Analytics 4) export to BigQuery writes one table per day, events_YYYYMMDD, with one row per event and nested, repeated records such as event_params and items25. An event is not a session. To get sessions, you have to build them, and Google's own help page explains the key: the session ID (ga_session_id) is the timestamp in seconds when the session started, so it is only unique in combination with the user, and Google suggests joining user_pseudo_id (or user_id) with the session ID to identify a session34.
-- models/marts/fct_sessions.sql (BigQuery dialect)
-- Grain: one row per GA4 session, identified by user_pseudo_id plus ga_session_id.
with events as (
select
user_pseudo_id,
(select value.int_value from unnest(event_params) where key = 'ga_session_id') as ga_session_id,
event_name,
timestamp_micros(event_timestamp) as event_at_utc,
device.category as device_category,
session_traffic_source_last_click.manual_campaign.source as source,
session_traffic_source_last_click.manual_campaign.medium as medium,
cast(ecommerce.purchase_revenue as numeric) as purchase_revenue -- FLOAT in the export
from {{ source('ga4', 'events') }}
where _table_suffix between '20260601' and '20260630'
)
select
{{ dbt_utils.generate_surrogate_key(['user_pseudo_id', 'ga_session_id']) }} as session_key,
user_pseudo_id,
ga_session_id,
min(event_at_utc) as session_start_utc,
cast(format_date('%Y%m%d', date(min(event_at_utc), 'Europe/London')) as int64) as session_date_key,
any_value(device_category) as device_category,
any_value(source) as source,
any_value(medium) as medium,
countif(event_name = 'page_view') as page_views,
countif(event_name = 'purchase') as ga4_purchases,
coalesce(sum(purchase_revenue), 0) as ga4_purchase_revenue
from events
where ga_session_id is not null
group by user_pseudo_id, ga_session_id
Two details deserve a comment. The source in a dbt project is declared with the wildcard table name events_*, which is what makes _table_suffix available. And purchase_revenue arrives as a floating point number, so it is cast to NUMERIC before any money is summed, for the reasons the chapter on data types sets out. In production this model is incremental, loading one day at a time, which a later chapter on incremental loading covers properly.
Example: one conversion rate, two honest answers
In June, fct_sessions holds about 110,000 sessions for Wrenfield Home. The shop recorded 1,980 orders. GA4 recorded about 15% fewer purchases, because of consent choices and blockers, which is
where is shop orders and is the share GA4 sees. The conversion rate is orders divided by sessions. See Foundations: ratios and rates.
where is the conversion rate, is the number of orders and is the number of sessions.
Using shop orders:
where is shop orders and is sessions.
Using GA4 purchases:
where is GA4 purchases.
So 1.80% against 1.53%. The model does not hide this. It keeps ga4_purchases on the session fact and real orders on the order facts, and the conformed date and channel dimensions let a report show both side by side with a label. What it never does is join individual sessions to individual orders as if GA4 saw every purchase. Why the two disagree, and how to reconcile them, is the subject of the article on when analytics, ads and orders disagree.
The example shop modelled in dbt
dbt (short for data build tool) is the open source tool that turns SQL select statements into tables and views in the warehouse, in dependency order, with tests and documentation alongside. Wrenfield Home's models follow dbt's own layering: staging models, one per source table, then marts for use35. The layers themselves, and the cleaning that happens in each, are the subject of chapter fifteen. Here the focus is the mart.
One honest note on names. dbt Labs' current guide names marts plainly after the entity (orders, customers) and recommends denormalising heavily unless you use their semantic layer35. Many teams, Wrenfield Home included, keep the Kimball prefixes fct_ and dim_ instead, because the prefix tells a reader the table's role at a glance. Either works. Picking one and sticking to it is what matters.
models/
staging/solidus/
stg_solidus__orders.sql
stg_solidus__line_items.sql
stg_solidus__variants.sql
stg_solidus__products.sql
marts/
dim_customer.sql
dim_date.sql
dim_product.sql
fct_order_lines.sql
fct_order_lines.yml
fct_sessions.sql
seeds/
uk_bank_holidays.csv
tests/
assert_allocated_shipping_matches_orders.sql
Example: fct_order_lines from the Solidus tables
The model below is written in BigQuery's dialect. It assumes staging models that keep the Solidus column names but rename id to order_id and line_item_id. The money logic follows Solidus itself: a line's amount is price * quantity, and its total adds adjustment_total, which holds promotions and any tax added on top but not tax already included in the price. UK prices include VAT, which Solidus records in included_tax_total3637.
-- models/marts/fct_order_lines.sql (BigQuery dialect)
-- Grain: one row per line item on a completed order.
{{ config(
materialized = 'table',
partition_by = {'field': 'order_date', 'data_type': 'date', 'granularity': 'month'},
cluster_by = ['product_key']
) }}
with orders as (
select order_id, order_number, user_id, email, shipment_total,
completed_at, canceled_at
from {{ ref('stg_solidus__orders') }}
where completed_at is not null
),
line_items as (
select line_item_id, order_id, variant_id, quantity, price, cost_price,
promo_total, included_tax_total, additional_tax_total
from {{ ref('stg_solidus__line_items') }}
),
lines as (
select
li.line_item_id,
o.order_id,
o.order_number,
o.user_id,
o.email,
o.completed_at,
o.canceled_at is not null as is_canceled,
li.variant_id,
li.quantity,
li.price * li.quantity as gross_item_amount,
li.promo_total as promo_amount,
li.price * li.quantity + li.promo_total + li.additional_tax_total as line_amount_incl_vat,
li.included_tax_total + li.additional_tax_total as vat_amount,
li.cost_price * li.quantity as cost_amount,
cast(round(o.shipment_total * 100) as int64) as order_shipping_pence,
cast(round((li.price * li.quantity + li.promo_total) * 100) as int64) as line_pence
from line_items as li
inner join orders as o on o.order_id = li.order_id
),
weighted as (
select
*,
sum(line_pence) over (partition by order_id) as order_items_pence,
row_number() over (partition by order_id order by line_item_id) as line_position
from lines
),
floored as (
select
*,
case
when order_items_pence = 0 then if(line_position = 1, order_shipping_pence, 0)
else div(order_shipping_pence * line_pence, order_items_pence)
end as shipping_floor_pence,
case
when order_items_pence = 0 then 0
else mod(order_shipping_pence * line_pence, order_items_pence)
end as shipping_remainder
from weighted
),
ranked as (
select
*,
order_shipping_pence - sum(shipping_floor_pence) over (partition by order_id) as pence_left,
row_number() over (
partition by order_id
order by shipping_remainder desc, line_item_id
) as remainder_rank
from floored
)
select
line_item_id,
{{ dbt_utils.generate_surrogate_key(['line_item_id']) }} as order_line_key,
order_number, -- degenerate dimension
{{ dbt_utils.generate_surrogate_key(['variant_id']) }} as product_key,
{{ dbt_utils.generate_surrogate_key([
"if(user_id is not null, concat('user:', cast(user_id as string)), concat('guest:', lower(trim(email))))"
]) }} as customer_key,
cast(format_date('%Y%m%d', date(completed_at, 'Europe/London')) as int64) as order_date_key,
date(completed_at, 'Europe/London') as order_date,
completed_at as completed_at_utc,
is_canceled,
quantity,
gross_item_amount,
promo_amount,
line_amount_incl_vat,
vat_amount,
line_amount_incl_vat - vat_amount as line_amount_excl_vat,
cost_amount,
cast(shipping_floor_pence + if(remainder_rank <= pence_left, 1, 0) as numeric) / 100
as allocated_shipping_amount
from ranked
Reading it from the top:
orderskeeps only completed orders. Baskets that never checked out are not sales.linescomputes every money column at line grain.promo_totalis negative in Solidus, so adding it subtracts the discount.weightedandflooreddo the largest remainder allocation in whole pence: the integer share rounded down (div) and what was left over (mod). An order whose lines are all free puts its whole shipping on the first line, so no penny is lost.rankedworks out how many pennies are still unallocated per order and ranks the lines by remainder.- The final select hands one extra penny to each of the top ranked lines, computes the hashed keys, and derives the UK date from the UTC timestamp.
The partitioning by month and clustering by product key are BigQuery storage choices that make date filtered and product filtered queries read less data3839. For 273,000 rows they barely matter. They are there because the habit is free and the shop will grow.
Example: the contract and the tests that guard the grain
A dbt model contract makes dbt check, before it builds, that the query returns exactly the declared columns with the declared types, and fail if it does not40. That protects every report downstream from a renamed or retyped column. The YAML below declares the contract, tests the grain, and checks that every fact row finds its product.
# models/marts/fct_order_lines.yml
models:
- name: fct_order_lines
description: "One row per line item on a completed order. Do not add order level amounts here without allocating them."
config:
contract:
enforced: true
columns:
- name: line_item_id
data_type: int64
constraints:
- type: not_null
- name: order_line_key
data_type: string
data_tests:
- unique
- not_null
- name: order_number
data_type: string
- name: product_key
data_type: string
data_tests:
- relationships:
arguments:
to: ref('dim_product')
field: product_key
- name: customer_key
data_type: string
- name: order_date_key
data_type: int64
- name: order_date
data_type: date
- name: completed_at_utc
data_type: timestamp
- name: is_canceled
data_type: bool
- name: quantity
data_type: int64
- name: gross_item_amount
data_type: numeric
- name: promo_amount
data_type: numeric
- name: line_amount_incl_vat
data_type: numeric
- name: vat_amount
data_type: numeric
- name: line_amount_excl_vat
data_type: numeric
- name: cost_amount
data_type: numeric
- name: allocated_shipping_amount
data_type: numeric
The relationships test checks referential integrity, that every product_key exists in dim_product. It skips nulls by design, so a separate not_null test is needed where nulls are not allowed41. This matters more than it looks on BigQuery: you can declare primary and foreign keys there, but BigQuery does not enforce them, and Google's documentation warns that queries over tables with violated constraints might return incorrect results, because the optimiser trusts what you declared42. On BigQuery, the dbt tests are the enforcement.
The allocation deserves its own check against the source: across every order, allocated shipping must add up to the order's shipping to the penny. A singular test in dbt is a select that returns the failing rows:
-- tests/assert_allocated_shipping_matches_orders.sql (BigQuery dialect)
-- Fails if any order's allocated shipping differs from what Solidus recorded.
select
o.order_number,
o.shipment_total,
sum(f.allocated_shipping_amount) as allocated
from {{ ref('stg_solidus__orders') }} as o
join {{ ref('fct_order_lines') }} as f
on f.order_number = o.order_number
group by o.order_number, o.shipment_total
having sum(f.allocated_shipping_amount) != o.shipment_total
And the tricky logic gets a unit test, run in development and in the test gate before release, on three hand made rows taken straight from the worked example above43. Here it is:
# models/marts/fct_order_lines_unit.yml
unit_tests:
- name: shipping_allocation_keeps_every_penny
model: fct_order_lines
given:
- input: ref('stg_solidus__orders')
rows:
- {order_id: 1, order_number: "R482913577", user_id: 7, email: "a@example.com",
shipment_total: 3.95, completed_at: "2026-06-01 09:14:00", canceled_at: null}
- input: ref('stg_solidus__line_items')
rows:
- {line_item_id: 11, order_id: 1, variant_id: 101, quantity: 1, price: 36.00,
cost_price: 15.00, promo_total: 0, included_tax_total: 6.00, additional_tax_total: 0}
- {line_item_id: 12, order_id: 1, variant_id: 102, quantity: 2, price: 14.00,
cost_price: 5.00, promo_total: 0, included_tax_total: 4.67, additional_tax_total: 0}
- {line_item_id: 13, order_id: 1, variant_id: 103, quantity: 1, price: 9.99,
cost_price: 3.00, promo_total: 0, included_tax_total: 1.67, additional_tax_total: 0}
expect:
rows:
- {line_item_id: 11, allocated_shipping_amount: 1.92}
- {line_item_id: 12, allocated_shipping_amount: 1.50}
- {line_item_id: 13, allocated_shipping_amount: 0.53}
Writing that test before the SQL is test driven development applied to data. If the idea is new to you, the article on test driven development explains why the test comes first. I work this way on every client project: the rule is written as a test, the test fails, the model makes it pass, and the release goes through a test gate before anything reaches a report.
One big table, and when it is the right answer
The opposite of a star is the one big table: every dimension column copied onto every fact row, so a report needs no joins at all. It has a serious following, and for good reasons. Spreadsheet users and many business intelligence (BI) tools work best with one flat table. dbt Labs' marts guidance leans the same way and recommends denormalising heavily when you are not using a semantic layer35. Google's BigQuery documentation recommends denormalising with nested and repeated fields, because joins cost network shuffling, while also noting that star schemas are already optimised for analytics, so denormalising further may not make a significant difference44.
Its weaknesses are just as real. When a dimension attribute changes (a product moves to a new category), every fact row carrying the old value must be rebuilt. Two one big tables built from the same facts can drift apart if one is refreshed and the other is not. And the one big table hides the grain: a flat table with order level columns copied onto lines invites somebody to sum order_shipping across lines.
The sensible pattern for a shop of Wrenfield Home's size is both: keep the star as the governed source, and build one big table from it for each audience that needs one, as a view or a small table, with the grain in its name.
Example: the spreadsheet export Priya actually uses
Priya likes to pivot in a spreadsheet. Callum builds obt_order_lines, which is fct_order_lines joined to dim_product, dim_customer (without personal data, see below) and dim_date. Over five years that is 273,240 rows, too many for a comfortable spreadsheet, so the export is filtered to the last 13 months: about rows, where is lines per month and is the number of months. It is rebuilt from the star every night, so it can never disagree with it. Because it is built from the star, its shipping column is the allocated one, safe to sum.
Inmon, Data Vault and where the dimensional model fits
The dimensional model is not the only school, and the other two deserve a fair hearing.
Bill Inmon described the data warehouse as an integrated, subject oriented store kept in a normalised form, from which departmental data marts are fed. His book Building the Data Warehouse reached its fourth edition in 200545. The strength is integration: one normalised enterprise model, independent of any single report. The cost is time and effort before the first useful report, which is why few small businesses start there.
Data Vault, created by Dan Linstedt and set out with Michael Olschimke in Building a Scalable Data Warehouse with Data Vault 2.0 (2015), models the raw history as hubs (business keys), links (relationships) and satellites (descriptive attributes with their history)46. It shines when many sources change often and auditability of every load matters, typical of large regulated organisations. It is not built for reporting directly, so a dimensional layer usually sits on top.
For a shop with a dozen sources, one data engineer and questions that change every month, the dimensional model on top of cleaned staging data is the best value: the shortest way from raw tables to numbers people can trust. If the business grows into dozens of teams and hundreds of sources, the capstone chapter of this series looks at what changes.
History, named only for now
One question has been waiting all chapter: what happens when a dimension changes? A customer moves from Leeds to Bristol. A product is moved from Living to Kitchen. If dim_product simply overwrites the category, then last year's revenue is suddenly reported under the new category, and last year's report can no longer be reproduced. Kimball calls the ways of handling this slowly changing dimensions: type 1 overwrites, type 2 adds a new row for each version with validity dates, and there are more. This is where the difference between a surrogate key (one version) and a durable key (the thing itself) earns its keep. Chapter seventeen of this series covers the types, dbt snapshots and reproducing any past report, in depth.
Personal data in dimensions
dim_customer is where personal data tends to pile up: names, emails, phone numbers, addresses. Most analysis needs none of it. Revenue by region needs the region, not the street. The UK GDPR's data minimisation principle says personal data must be adequate, relevant and limited to what is necessary for the purpose47. In modelling terms: keep the identifying columns in one restricted table (or in the source), and give dim_customer only what analysis needs, such as first order date, region, customer type and the surrogate key. The customer_key hash is not anonymisation, because anyone with the input can recompute it, so it is still personal data in law. A later chapter on privacy engineering covers retention and erasure in pipelines. This is general information, not legal advice.
Example: what goes in dim_customer
| Column | In dim_customer | Reason |
|---|---|---|
customer_key | yes | the join key |
first_order_date | yes | cohorts and new against returning |
customer_region (for example Yorkshire and the Humber) | yes | regional reporting |
has_account | yes | guest against account behaviour |
| email, name, phone, street address | no, restricted table only | not needed for analysis |
With that split, the cohort analysis Priya runs every quarter works entirely from the star, and nobody who reads a dashboard ever sees a customer's email.
A checklist for every new fact table
| Step | Question to answer | Done when |
|---|---|---|
| 1 | Which business process is this? | One process named, for example "customer returns" |
| 2 | What is the grain? | One sentence, a unique key, a uniqueness test |
| 3 | Which dimensions apply at this grain? | Every dimension single valued per row, or a bridge with weights |
| 4 | Which facts, and are they additive? | Additive parts stored, ratios computed later, semi additive ones labelled |
| 5 | Any facts at a coarser grain? | Allocated with a written rule and a test, or kept in their own table |
| 6 | Which dates, in which time zone? | Role playing date keys, local date rule written, UTC timestamp kept |
| 7 | What if a dimension row is missing? | Points at the Unknown row, orphans counted |
| 8 | Is it guarded? | Contract, unique, not null, relationships, a reconciliation test against the source |
| 9 | Is personal data needed here? | Only what analysis needs, the rest restricted |
Conclusion
The shop database is shaped for taking orders, not for answering questions about them. A dimensional model reshapes the data once, in tested code, so that the right answer is also the easy one. Declare the grain in one sentence before anything else, and never mix grains in one table. Store additive facts and compute ratios after summing. Allocate order level amounts to lines with a rule that keeps every penny, or keep them at order grain. Flatten dimensions, give every row a surrogate key and every missing value a readable label, and keep one category per product unless you build a proper bridge. Choose the fact table type that fits the process, and decide your reporting time zone in writing.
For Wrenfield Home, that turned a £160,470 answer into £134,640, with a bridge to finance's £142,560 and £118,800 that comes out the same every month. The next chapter, on SQL traps, shows the queries that still go wrong on a good model, and how to catch them before they reach Priya.
