Hands-on lab · DuckDB · one day
Facts, Dimensions
& Everything Between
Build the dimensional warehouse for a €14M outdoor-gear webshop — then answer the questions its board actually asks.
Press → or click Next. Press g for the slide map.
Welcome. No SQL for the first twenty minutes — we start with why anyone cares.
Set expectations: by 16:00 they will have a working star schema and answers to questions they could not answer this morning.
Background
A climbing shop that accidentally became a webshop
Windrose Supply Co., Utrecht. Four channels, two distribution centres, three currencies, one operational database and no data warehouse.
Keep this light — 3 minutes. The point is that windrose is a normal business, not a textbook. Every channel arrived as a new table, every new market added a currency and a warehouse, and nobody ever redesigned the reporting.
The people
Six numbers, four people, no agreement
Maud de Vries
Founder & CEO“Is the growth real, and are my customers loyal — or just cheap?”
Ruben Aalders
CFO“I have six numbers and none of them reconcile. Give me one.”
Sanne Bakker
Head of e-commerce“Which products, channels and campaigns actually earn money?”
Maarten
Operations“Why is Munich slower than Utrecht, and what runs out next?”
“One version of the truth. Ten questions. Three weeks.”
What they actually need is not ten queries. It is a model that makes all ten answerable — and keeps them answerable next quarter, when someone adds a channel, a currency or a warehouse.
Name the tension: the business is not asking for a star schema. It is asking for numbers to stop contradicting each other. The star schema is how you get there.
The starting point
What “reporting” looks like today
The operational database was built to take orders, not to answer questions. It has everything and it has nothing:
- 23 tables, no foreign keys, no history except where an app developer happened to add it
- No surrogate keys — the customer table has no idea it once had three versions of a person
- Mutable rows — an address is overwritten, so “where did this customer live in March” is unanswerable
- Three status vocabularies for one order, across two teams
- Hand-typed codes —
"web ","App"," Store"are three different channels - Test accounts that have been ordering since 2024 and appear in every total
-- the order table, as it exists ORDERS order_id integer order_number varchar -- 'WR-2025-000123' customer_id integer -- no FK. 31 ghosts. channel_id integer order_ts timestamp order_status varchar -- 5 values, 3 spellings currency_code char(3) -- EUR, USD, CHF promotion_code varchar -- nullable, free text is_gift boolean delivery_speed varchar ... -- and no price history anywhere.
23 tables like this. 1.2 million rows. No documentation.
Do not rubbish the source. It is a perfectly good order system. It is simply not a warehouse, and expecting it to behave like one is where the six numbers come from.
An example
One question. Two queries.
click the tabs“Monthly net revenue and gross margin by department, 2026 H1.”
-- 7 joins, 3 CTEs, and a decision per line WITH rate AS ( SELECT rate_date, from_currency, rate FROM currency_rates WHERE to_currency = 'EUR' ), eligible AS ( SELECT o.order_id, o.order_ts, o.currency_code, o.channel_id, ol.variant_id, ol.quantity, ol.unit_price, ol.discount_amount, ol.tax_amount FROM orders o JOIN order_lines ol ON ol.order_id = o.order_id WHERE o.order_status IN ('COMPLETED', 'SHIPPED', 'RETURNED') AND ol.line_status = 'ACTIVE' AND o.customer_id NOT IN (SELECT customer_id FROM customers WHERE is_test_account) ), priced AS ( SELECT e.*, p.list_price, p.cost_price, p.category_id FROM eligible e JOIN product_variants v ON v.variant_id = e.variant_id JOIN products p ON p.product_id = v.product_id ), typed AS ( SELECT p.*, c3.category_name AS line, c2.category_name AS fam, c1.category_name AS dept FROM priced p LEFT JOIN categories c3 ON c3.category_id = p.category_id LEFT JOIN categories c2 ON c2.category_id = c3.parent_category_id LEFT JOIN categories c1 ON c1.category_id = c2.parent_category_id ) SELECT DATE_TRUNC('month', t.order_ts) AS month, COALESCE(t.dept, 'Unassigned') AS dept, SUM(((t.unit_price * t.quantity) - t.discount_amount) * COALESCE(r.rate,1)) AS revenue, SUM(((t.unit_price * t.quantity) - t.discount_amount - t.cost_price * t.quantity) * COALESCE(r.rate,1)) AS margin FROM typed t LEFT JOIN rate r ON r.rate_date = CAST(t.order_ts AS DATE) AND r.from_currency = t.currency_code WHERE t.order_ts >= '2026-01-01' AND t.order_ts < '2026-07-01' GROUP BY 1, 2 ORDER BY 1, 2;
What just happened
- 74 lines, and every one is a decision someone will disagree with
- The status filter is a business rule hiding in a
WHERE - The FX join silently drops rows when a rate is missing
- The category roll-up breaks on the two deleted categories
- Write it again for returns, and again for delivery, and hope they agree
The quiet problem
Nothing here is wrong. It is unrepeatable. The next analyst writes a subtly different version, and now Ruben has seven numbers.
-- the same answer, against DW SELECT d.year_month , p.department_name , ROUND(SUM(f.net_amount_eur), 2) AS revenue , ROUND(SUM(f.margin_amount_eur), 2) AS margin FROM windrose.dw.fact_sales f JOIN windrose.dw.dim_date d ON d.date_key = f.order_date_key JOIN windrose.dw.dim_product p ON p.product_key = f.product_key WHERE d.year_number = 2026 AND d.month_number <= 6 GROUP BY 1, 2 ORDER BY 1, 2;
COALESCE on a deleted category. All of that was decided once, in the
model, where it can be reviewed and tested.
Where the logic went
| status filter | FACT_SALES load |
| FX conversion | exchange_rate on the fact |
| category roll-up | DIM_PRODUCT |
| “what is a month” | DIM_DATE |
| test accounts | excluded once, tested once |
The real difference
The second query cannot drift. Every future report that says “revenue” gets the same number, because there is only one place the number can come from.
This is the emotional centre of the opening. Let them read the long query for a moment. Then flip. Then ask: "which one would you want to change at 17:00 on a Friday?"
Point out that the long query is not stupid — it is what a competent analyst writes when there is no model. The model is what stops the next twelve analysts writing it again.
The shape
One fact, many dimensions, zero ambiguity
2 degenerate ids
9 measures
Every arrow is an integer equality. No BETWEEN, no LIKE, no business rule.
Grain
One row per order line. Stated before the table is written, and every other decision has to respect it.
Keys
Integers, not natural keys. 0 is unknown,
-1 is “not applicable”. Never a NULL foreign key.
Measures
Additive where possible. Semi-additive where honest. Non-additive ratios never stored.
Do not over-explain the diagram. The point is the shape: one fact, symmetric joins, integer keys. Everything else today is a variation on this.
The goal
What we are going to build today
The model
deliverable- 16 dimensions — conformed, keyed, with unknown members
- 7 fact tables — one per business process, at a declared grain
- 1 bridge — because promotions cover many products
- 34 quality tests — all green, or the model is not done
The answers
proofEighteen questions, each answerable in under twenty lines against your own star — with the same numbers as the person next to you.
The four sentences you must be able to say
- “One row in this fact represents ….”
- “This dimension is unique on …, and here is the unknown member.”
- “This customer fact joins on the version that was valid at the time.”
- “This measure is additive across … and not across ….”
Be concrete about the deliverable. Participants should leave with a working model, not notes about one. Point at sql/assignments/ — that is the work.
The source system
23 tables, no foreign keys
click a tableA nightly replica of the webshop's operational database,
landed in WINDROSE.SRC. This is what you are given.
Reference
People
Catalogue
Transactions
Web
Pick a table
Each table shows its grain, its key, and the one thing that will bite you.
23 tables · ~1.2M rows · 0 foreign keys — the full dictionary, including all 15 known defects, is in docs/source-system.md.
Do not tour all 22. Pick five: ORDERS, ORDER_LINES, CUSTOMERS, CUSTOMER_TIER_HISTORY, INVENTORY_SNAPSHOTS. The rest they can read in docs/source-system.md.
Emphasise: these are natural keys and mutable rows. There is no history for price, and no current-tier flag on the customer. That is deliberate.
The source system
Twenty-three tables, no foreign keys
drag to pan / scroll to zoomEvery line below is inferred from a column name. The database enforces none of them — which is why 31 orders point at customers that do not exist.
─── foreign key, by id
╌╌╌ joined on values, not a key
1 ──< N one to many
Pick a table
Click any box in the diagram to isolate its relationships.
Do not trace every line. Click ORDERS first: it is the hub, and every arrow is a decision the warehouse will have to make.
Then click CUSTOMER_TIER_HISTORY — a table with a validity date and no current flag. That is the raw material for the Type-2 dimension this afternoon.
The dashed line is worth thirty seconds: CURRENCY_RATES has no key at all. It joins on date plus currency code, which is exactly the kind of join that silently drops rows when a rate is missing.
The payoff
Same question. Four ways to ask it.
“How much did German customers spend on tents?” — asked of the source, then again after each piece of the star is built. The answer never changes. The query does.
Click through 0 → 3. The point is not that the query gets shorter; it is that the question gets clearer. At step 0 the analyst has to know that a customer's country is the address that was valid on the order date, that cancelled lines are excluded, and that a two-level category has to be rolled up by hand.
At step 3 none of that knowledge is needed. It lives in the model, where it was reviewed once.
Say out loud that the number is the same at every step — €1,270,040 — because that is what makes this a refactor rather than a rewrite.
The source system
The eight things that will bite you
1 · Codes typed by hand
"web ", "App", " Store". Join on the raw code and you silently lose a quarter of your revenue.
2 · 31 ghost customers
Orders whose customer_id is not in the customer table. Drop them and €9.7k of revenue vanishes.
3 · 15 test accounts
Internal QA accounts, ordering since 2024, counted in every per-customer average.
4 · Timestamps stored as text
WEB_SESSIONS.session_start is a VARCHAR in two formats. The classic “quick dashboard” bug.
5 · Negative order lines
Manual corrections, 0.4% of lines. Real rows. SUM() handles them; WHERE quantity > 0 hides them.
6 · Two SKUs without cost
Margin is unknown, not zero. COALESCE(cost, 0) invents a 100% margin.
7 · Two broken categories
One deleted, one with a missing parent. A three-level join drops those products without a warning.
8 · Sessions that never happened
10% of digital orders have no session at all. Revenue without a session is a category, not a bug.
Ask the room which quirk has burned them before. It always produces a story, and the story is better than the slide.
The questions
Eighteen questions the model has to survive
filter- Q01Is the business growing?role-playing date
- Q02Which parts of the assortment make money?flattened hierarchy
- Q02BThe same question through a snowflakesnowflake vs star
- Q03What sells a lot but earns very little?NULL cost, additive measures
- Q04Where do sales come from, and is that changing?conformed channel
- Q05Did the promotions pay for themselves?“no promotion” baseline
- Q06Are we acquiring customers or churning?first-purchase detection
- Q07Which loyalty tier is worth the most?SCD2 as-of vs is_current
- Q08Do the customers we win in a month stay?cohort analysis
- Q09Where do our customers go?Type-2 geography
- Q10Do discount-acquired customers come back?grain conversion
- Q11Where does revenue leak back out?fact-to-fact
- Q12How fast do we ship, and who is late?accumulating snapshot
- Q13What was on promotion and still did not sell?factless fact
- Q14How much stock do we hold, and where?semi-additive snapshot
- Q15What is about to run out?snapshot ⋈ event fact
- Q16Do gifts and express change basket size?junk dimension
- Q17Which traffic is worth paying for?event fact, soft link
- Q18How much of our growth is the exchange rate?multi-currency fact
Do not read all eighteen. Ask the room to pick the three they find hardest. It is almost always Q07, Q13 and Q14 — which is why those three get their own slides.
Every question has a reference answer in sql/questions/ and an expected insight in docs/questions.md.
The questions
Three of them cannot be answered by the model you are imagining
Each one forces a pattern. Get these three right and the other fifteen are ordinary SQL.
Which tier was this customer in when they bought?
The customer table only knows who they are now. You need a version of the customer that was valid on the order date.
Forces: SCD Type 2 and the as-of join.
Which products were on promotion and never sold?
The sales fact has no row for a non-event. You cannot group by an absence, and you cannot count what is not there.
Forces: a factless fact table that records coverage.
How much stock do we hold — in total?
Stock is measured every day. Adding yesterday to today is not a bigger number, it is a wrong one.
Forces: semi-additive measures and a snapshot fact.
This is the bridge into the patterns section. Do not solve them yet — just make the room feel the shape of the problem.
The patterns
The pattern zoo
click a cardTwelve names you will hear all day. Each card says what it is and where it lives in this model.
Do not flip all twelve. Flip the three the room asks about. The back of each card is the answer to "where would I ever use that?"
Pattern · SCD Type 2
One customer, three versions of herself
| customer_key | customer_id | city | tier | valid_from | valid_to |
|---|---|---|---|---|---|
| 41 | 4711 | Utrecht | Bronze | 2024-02-11 | 2025-03-01 |
| 88 | 4711 | Utrecht | Silver | 2025-03-01 | 2025-09-14 |
| 152 | 4711 | München | Silver | 2025-09-14 | 9999-12-31 |
Two different change streams — a tier upgrade and a move — merged onto one timeline.
-- the only correct way to join history JOIN dim_customer c ON c.customer_id = o.customer_id AND o.order_date >= c.valid_from AND o.order_date < c.valid_to
Half-open, always
With inclusive intervals, an order placed on the day she moved matches both Utrecht and München, and the revenue doubles. Half-open makes that impossible.
Built from events, not snapshots
Collect every date something changed, look up what was
true on that date, then close the intervals with LEAD(). No daily
snapshot table required.
The shortcut that looks right
WHERE is_current gives you one row per
customer, joins cleanly, and credits every historical order to their current
status. It runs. It is wrong.
Walk the three rows. Ask: "if she orders on 2025-09-14, which row?" The answer is the third, because valid_from is inclusive. That single moment teaches half-open intervals better than any definition.
Pattern · the trap
Two correct queries. One honest answer.
Q07: which loyalty tier is worth the most? Revenue by the tier held at the time of the order, versus the tier held today.
| Tier | Orders | Revenue — tier at order time | Revenue — tier today | Difference |
|---|---|---|---|---|
| Bronze | 24,718 | €12,263,383 | €11,363,576 | −€899,808 |
| Silver | 2,969 | €1,533,425 | €2,344,362 | +€810,937 |
| Gold | 419 | €228,785 | €308,158 | +€79,373 |
| Platinum | 24 | €10,172 | €19,670 | +€9,498 |
Why this is the whole course
No error message. No blank page. Just a number that is wrong by enough to change a decision, and a colleague with a different number. The as-of join is the difference between a warehouse and an argument.
Ask: "which number would you have put in the board pack?" Then: "and how would you have known?" That is the case for testing and for documenting the grain.
Pattern · fact-to-fact
Link facts only when the grain matches
Returns → Sales
worksBoth are one row per order line. The return carries
originating_sales_line_key.
SELECT r.return_quantity, r.refund_amount , f.unit_price AS price_paid FROM fact_returns r JOIN fact_sales f ON f.sales_line_key = r.originating_sales_line_key
Why it matters: the refund is measured against the price actually paid, including any discount.
Payments → Sales
multipliesPayments are per order, sales are per line. Joining directly multiplies the payment by the number of lines.
| order | payment | lines | naive join |
|---|---|---|---|
| WR-2025-000418 | €412 | 3 | 3 × €412 |
Fix: aggregate one side to the other's grain
first. V_SALES_ORDER_GRAIN exists for exactly this.
DISTINCT to a fact join, stop and read the grain.
This is the slide that saves the most production incidents. The tell is
SUM(DISTINCT …) or a mysterious 3× multiplier.
Pattern · factless fact table
How do you query something that never happened?
Q13: which products were on promotion and never sold a single unit?
Why the sales fact cannot answer it
There is no row for a non-sale. You cannot
GROUP BY an absence, and COUNT(*) of nothing is zero —
which is exactly the answer, but with no product attached to it.
So we record the offer, not the sale
One row per product, per promotion, per day it was live. No measures at all. Then anti-join to sales.
-- FACT_PROMOTION_COVERAGE has keys only SELECT p.product_name, pr.promotion_code, COUNT(*) AS days_on_promotion FROM fact_promotion_coverage c JOIN dim_product p ON p.product_key = c.product_key JOIN dim_promotion pr ON pr.promotion_key = c.promotion_key WHERE NOT EXISTS ( SELECT 1 FROM fact_sales f WHERE f.product_key = c.product_key AND f.promotion_key = c.promotion_key ) GROUP BY 1, 2 ORDER BY 3 DESC;
COUNT(*). The row is the fact. That is not a
technicality — it is the only way to count things that did not happen.
Let them try to write it against FACT_SALES first. Two minutes of failing is worth more than the finished query.
Pattern · semi-additive measures
Stock is not sales
| SKU | Mon | Tue | Wed | SUM | AVG |
|---|---|---|---|---|---|
| TENT-0034 | 120 | 118 | 131 | 369 | 123 |
| PACK-0017 | 80 | 80 | 74 | 234 | 78 |
| Total | 200 | 198 | 205 | 603 | 201 |
603 units is not a quantity of anything. It is the same warehouse counted three times.
Additive across
Products, warehouses — two shelves really do hold twice the stock.
Never additive across
Dates. Stock is a balance, not a flow.
So: average, or last day
AVG() if you want a rate for the period,
the final snapshot if you want a balance. Q14 shows both — and prints the wrong
answer next to them.
Ask the room: "what else in your business is a level, not a flow?" Bank balances and headcount always come up. That is the transferable idea.
Pattern · junk dimension
Four flags, one small table
Gift, delivery speed, device, marketing source. Nothing in common except that they describe an order and each has fewer than ten values.
| theoretical combinations | 2 × 4 × 6 × 6 = 288 |
| combinations that occur | 137 |
| columns added to the fact | 1 |
| columns NOT added to the fact | 4 |
-- with the junk dimension SELECT fl.is_gift, fl.delivery_speed, COUNT(DISTINCT f.order_number) AS orders, ROUND(SUM(f.net_amount_eur) / COUNT(DISTINCT f.order_number), 2) AS aov FROM fact_sales f JOIN dim_order_flags fl ON fl.order_flags_key = f.order_flags_key GROUP BY 1, 2;
Without it
Four more columns on 53,000 fact rows, four filters in every query, and every new flag becomes a migration instead of a few new rows.
The rule of thumb
Low cardinality, no attributes of their own, used together → junk dimension. If one flag has a hierarchy (country → region), give it its own dimension.
The common objection: "why not just put the flags on the fact?" Answer: you can, and then the fact has 15 boolean columns that every query has to filter, and no one agrees which combination means 'gift express'.
The target model
Seven facts, sixteen dimensions, one bridge
Dimensions
Facts
| FACT_SALES | 52,868 |
| FACT_RETURNS | 4,065 |
| FACT_PAYMENTS | 32,730 |
| FACT_ORDER_FULFILLMENT | 29,073 |
| FACT_INVENTORY_SNAPSHOT | 327,600 |
| FACT_PROMOTION_COVERAGE | 19,183 |
| FACT_WEB_SESSIONS | 151,805 |
Plus
BRIDGE_PROMOTION_PRODUCT (474 rows) and
AGG_SALES_MONTHLY (503 rows) to show aggregate navigation.
Do not read the list. Point at the two shapes: four of the seven facts are not transaction facts. That is the point — a warehouse is not a copy of the order table.
The target model
The bus matrix is the design
Rows are business processes, columns are conformed dimensions. If two facts share a column, their numbers can be compared without reconciliation.
| Fact | Date | Time | Cust | Demo | Prod | Chan | Promo | Flags | Pay | WH | Carrier | Reason | Traffic |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| SALES | ● | ● | ● | ● | ● | ● | ● | ● | · | ● | ● | · | · |
| RETURNS | ● | ● | ● | ● | ● | ● | · | ● | · | · | · | ● | · |
| PAYMENTS | ● | ● | ● | · | · | · | · | · | ● | · | · | · | · |
| FULFILLMENT | ●×4 | · | ● | · | · | ● | · | ● | · | ● | ● | · | · |
| INVENTORY | ● | · | · | · | ● | · | · | · | · | ● | · | · | · |
| COVERAGE | ● | · | · | · | ● | · | ● | · | · | · | · | · | · |
| SESSIONS | ● | ● | ● | · | · | ● | · | · | · | · | · | · | ● |
Date appears 7 times
Role-playing. One table, many foreign keys.
Customer appears 4 times
The conformed dimension that makes cohorts, tiers and geography agree.
Traffic appears once
And that is fine. Not every dimension belongs in every fact.
The bus matrix is the deliverable of week one in real life. Here it is the answer to "which dimensions do I build first?" — the ones with the most dots.
Conventions
Six rules that stop the arguments
1 · Surrogate keys are integers
customer_key, not customer_id. The
natural key stays in the dimension for lineage.
2 · 0 unknown, -1 not applicable
Two different facts about an event. “No promotion” is not “we lost the promotion code”.
3 · Half-open SCD2 intervals
valid_from <= date < valid_to, current row
ends 9999-12-31. Never BETWEEN.
4 · No NULL foreign keys
A NULL key drops the row from every inner join, silently. Use the unknown member.
5 · Date keys are integers
yyyymmdd. Readable in a result, joinable, and
sortable without a cast.
6 · Grain first, always
If you cannot write “one row represents …” in one sentence, stop. You are about to build two facts by accident.
These are in AGENTS.md and docs/model-design.md. Tell participants where to find them — they will forget by 14:00.
Validation
A star schema fails silently
A duplicated dimension row does not raise an error. It doubles revenue in one report and not another, and the argument about which number is right takes a week.
34 invariant tests, one gate
- Surrogate keys unique in every dimension
- Exactly one current row per natural key
- No overlapping SCD2 intervals
- Every fact key resolves to a dimension member
- Fact row count equals the source row count
- Returns never exceed what was sold
- Captured payments reconcile to order totals
- Milestones move forward in time
- Bridge weights sum to one per product
SELECT status, COUNT(*) AS checks FROM windrose.qa.test_results GROUP BY status; -- status checks -- ------ ------ -- PASS 34 -- and if it is not: SELECT check_name, actual FROM windrose.qa.test_results WHERE status = 'FAIL';
Tell the cancelled-payment story: the JOIN to order lines filtered on ACTIVE, cancelled orders have no ACTIVE lines, so 900 payments disappeared. No error. The reconciliation test found it.
That's the day
Now go and model something.
The patterns are forgettable. The four sentences are not: grain, unique key, as-of join, additive across what.
← to revisit anything · g for the slide map · p to print
Close on the grain sentence. It is the one habit that survives the course.
Full-screen tool: the Query tab is the editor and results, Database is the schema browser, Lineage draws where a view's data comes from.
The bar between the editor and the results is draggable — pull it down for long SQL, up for a big result set. Double-click it to reset, and the height is remembered.
dim_date, dim_time and dim_channel are already
there as views — the two spines nobody should spend the morning typing, and the smallest
dimension to copy the shape from (surrogate key, cleaned attributes, the 0 member).
Say so out loud: participants will otherwise assume they built them, and the point of
dim_channel is that they can CREATE OR REPLACE it in one line
when they want their own.
Views live in this page's memory, so a reload resets the database. That is deliberate: each participant gets a clean slate, and nothing they do can break anyone else's.
First run downloads the 34 MB engine plus the Parquet files from this folder — once. After that every query is local and instant, and it works with the wifi off.
Worth doing live: join fact_sales to fact_payments and watch
the fan-out, then fix it by aggregating to order grain first. Then create a view on top
and open Lineage to show the dependency chain.