IntermediateData Modeling · 30 min · 12 challenges

Star Schemas

Prime Day has ended at Amazon, and a category manager wants units sold by product category, by hour, by fulfillment center before the morning review. Every item sold is one row somewhere. Whether her answer arrives in seconds or after a week of untangling joins depends on one design: measurements in the middle, descriptions around them.

The Star Schema

Daily Life
Interviews
Fernhill Outdoor sells camping gear online. Its order system is in 3NF, which keeps writes safe: each fact about a product or a customer lives in exactly one place. The cost shows up when an analyst asks for revenue by product category by month.

That question needs 4 joins across 5 tables (order_lines, orders, products, subcategories, categories) to produce 2 grouping columns and one sum. A different question tomorrow needs a different chain of joins. Analytical work asks hundreds of these questions, so the warehouse, the copy of the data kept for analysis, is reshaped around the questions.

One fact table, many dimensions

A star schema sorts every column into one of 2 kinds of table. A fact table holds measurements of a business event: quantities and amounts you can add up. A dimension table holds the descriptions you filter and group by: the product's name and category, the customer's city, the calendar month. The fact table sits at the center and carries one foreign key to each dimension.
fact_order_line
date_keyFKINTEGER
product_keyFKINTEGER
customer_keyFKINTEGER
order_numberBIGINT
quantityINTEGER
net_amountDECIMAL(12,2)
dim_date
date_keyPKINTEGER
full_dateDATE
day_of_weekVARCHAR
month_nameVARCHAR
year_monthVARCHAR
calendar_yearINTEGER
fiscal_quarterVARCHAR
is_holidayBOOLEAN
dim_product
product_keyPKINTEGER
skuVARCHAR
product_nameVARCHAR
subcategoryVARCHAR
categoryVARCHAR
brandVARCHAR
dim_customer
customer_keyPKINTEGER
customer_nameVARCHAR
cityVARCHAR
countryVARCHAR
loyalty_tierVARCHAR

One row of fact_order_line means one product on one order. One row of dim_product means one product, and that row also carries the product's subcategory and category. The categories and subcategories tables are gone, folded into the product they describe.

That folding is the strategic denormalization you already know, applied on purpose. The category name 'Shelter' repeats on every tent and tarp row, and the redundancy is cheap: a dimension has thousands of rows, is loaded by one pipeline, and is read far more than it is written. The order_number column stays on the fact row with no table of its own, a choice the dimensions section returns to.

Every question has the same shape

Revenue by category by month now reads like this.
SELECT
p.category,
d.year_month,
SUM(f.net_amount) AS revenue
FROM fact_order_line AS f
JOIN dim_product AS p
ON f.product_key = p.product_key
JOIN dim_date AS d
ON f.date_key = d.date_key
WHERE d.calendar_year = 2026
GROUP BY p.category, d.year_month
ORDER BY p.category, d.year_month

Each dimension is one join away from the fact table. Swap p.category for c.loyalty_tier, or d.year_month for d.day_of_week, and the query keeps its skeleton. You join the dimensions you need and filter on their attributes, then group and sum the facts. The join path never has to be worked out again for a new question.

Why the shape is fast

The 2 kinds of table have opposite proportions. A fact table is long and narrow: hundreds of millions of rows, each a handful of integer keys and numbers. A dimension is short and wide: dim_product might hold 40,000 rows and 30 text columns. A filter such as category = 'Shelter' can run against the 40,000-row table first and yield a small set of product keys. The engine then scans the fact table comparing integers, never long strings.

Fact table
  • Measurements of an event
  • Many rows, few columns
  • Foreign keys plus numbers
  • Grows with every event
Dimension table
  • Descriptions of a thing
  • Few rows, many columns
  • One key plus text attributes
  • Grows when a new product or customer appears
The star has a price. It's a second copy of the data, so a pipeline must keep it loaded. A dimension repeats values, so a renamed category must be rewritten on every product row that carries it. And a star answers the questions its fact table measured: if nobody recorded discounts on the order line, no join will produce them.
Multiple Choice

An analyst at Fernhill wants units sold by customer loyalty tier and day of week. What does the star above need before this query can run?

Reading any star starts with 3 questions. What does one row of the fact table mean? Which descriptions hang off it? Which numbers can be summed? The next sections take the 2 kinds of table apart, starting with the fact table, which comes in 3 forms.

Types of Fact Tables

Daily Life
Interviews
Fernhill's operations team asks 3 questions in one week. How much did we sell yesterday? How much stock is in each warehouse right now? How long does an order take to reach the customer? Each one measures the business differently, and each needs a fact table with a different rhythm of rows.

Transaction: one row per event

A transaction fact table records an event at the moment it happens. fact_order_line is one: a customer buys 2 headlamps, and a row lands with the date, the product, the customer, a quantity of 2 and an amount of 59.90. The row is written once and never touched again. If nothing sells, nothing is written, so the table is sparse: a product with no sales on Tuesday has no Tuesday row.

That sparseness is why a transaction table struggles with the stock question. Stock on hand adds up every receipt since the warehouse opened and subtracts the sales, with returns added back. Deriving it means replaying the whole history for every product, every time someone asks.

Periodic snapshot: one row per period

A periodic snapshot fact table measures a level at a fixed interval. Every night, fact_inventory_daily gets one row for every product in every warehouse, holding the quantity on hand at close of day. The table is dense: a tent that nobody touched still gets its row, saying 14 again.

fact_order_line (transaction)
date_keyproductquantity
20260302Ridge 2P Tent1
20260304Ridge 2P Tent2
fact_inventory_daily (snapshot)
date_keyproductquantity_on_hand
20260302Ridge 2P Tent14
20260303Ridge 2P Tent14
20260304Ridge 2P Tent12

On 3 March (date_key 20260303) the left table says nothing and the right table says 14. That row for a day without events is the whole point of a snapshot. The price is volume: 40,000 products in 6 warehouses come to 240,000 new rows each night, even on a night with no sales. A snapshot row is also a level, so read one date at a time: adding the 14 from 2 March to the 14 from 3 March counts the same tents twice.

SELECT
p.category,
SUM(i.quantity_on_hand) AS units_on_hand
FROM fact_inventory_daily AS i
JOIN dim_product AS p
ON i.product_key = p.product_key
WHERE i.date_key = 20260304
GROUP BY p.category

Accumulating snapshot: one row per process

The delivery question is about a process with known milestones: an order is placed and packed, then shipped, then delivered. An accumulating snapshot fact table holds one row per order for its whole life. The row is inserted when the order is placed, with the later milestone dates empty. Each time the order reaches a milestone, the pipeline goes back and updates that same row.
As ofplaced_date_keyshipped_date_keydelivered_date_keydays_to_shipdays_to_deliver
2 March20260302not yetnot yetnot yetnot yet
4 March2026030220260304not yet2not yet
7 March20260302202603042026030725

All 3 lines of that table are the same row of fact_order_fulfillment, read on 3 different days. Because every milestone sits on one row, the time between them is a subtraction. The table stores the results as days_to_ship and days_to_deliver. Average delivery time by warehouse becomes one AVG over one column. Building the same answer from a transaction table means finding each order's 'shipped' event and its 'delivered' event and pairing them up.

The cost is the update. This is the only one of the 3 forms whose rows change after they're written, so its pipeline must find and rewrite rows instead of appending them. It also fits only a process with a fixed, short list of milestones. A support ticket that can bounce between teams any number of times has no fixed columns to fill.

Choosing between the 3

PropertyTransactionPeriodic snapshotAccumulating snapshot
One row isOne eventOne entity in one periodOne run of a process
Rows appearWhen an event happensOn a schedule, event or notWhen the process starts
Rows changeNeverNeverAt every milestone
AnswersHow much happened?What was the level?How long did each step take?
Fernhill tablefact_order_linefact_inventory_dailyfact_order_fulfillment
Multiple Choice

Fernhill's finance team wants the outstanding gift card balance for every card at the end of each month, including cards nobody used that month. Which fact table fits?

One test separates the 3: ask when a row is born and whether it ever changes. Born with an event and frozen is a transaction. Born on a schedule and frozen is a periodic snapshot. Born with a process and revised until the process ends is an accumulating snapshot.

Types of Dimensions

Daily Life
Interviews

A fact row for order 5001 says: date 20260302, product 318, customer 7741, quantity 1, amount 249.00. Those numbers mean nothing until a dimension translates them. Dimensions are where the words live, and the words are what analysts type into WHERE and GROUP BY.

Anatomy of a dimension row

A dimension has one row per thing being described and one column per way of describing it. Hierarchies are flattened onto the row: a tent's subcategory and category sit beside its name. Codes are spelled out: the row says 'Shelter', never category 3, because the report will print whatever the column holds.
product_keyskuproduct_namesubcategorycategorybrand
318TNT-204Ridge 2P TentBackpacking TentsShelterFernhill
319TNT-310Basecamp 6P TentFamily TentsShelterFernhill
502LGT-011Beam 400 HeadlampHeadlampsLightingLumora

More columns make a better dimension. Each attribute added to dim_product is a new way to slice every fact table that points at it, at the cost of one column on a 40,000-row table.

The date dimension

Almost every star has a date dimension: one row per calendar day, built once for decades ahead. A DATE column can already give you the month, but it cannot tell you the fiscal quarter, whether the day was a public holiday, or which week of Fernhill's spring sale it fell in. dim_date stores those as plain columns, so 'sales on holidays' is a filter instead of a formula every analyst writes differently.

Conformed: one dimension, many stars

Fernhill has 2 fact tables that mention products: fact_order_line and fact_inventory_daily. A conformed dimension is one that both use with the same keys and the same attribute values. Because 'Shelter' means the same set of products in both stars, units sold by category and units on hand by category can sit in adjacent columns of one report.

fact_order_line
date_keyFKINTEGER
product_keyFKINTEGER
quantityINTEGER
net_amountDECIMAL(12,2)
dim_product
product_keyPKINTEGER
product_nameVARCHAR
categoryVARCHAR
fact_inventory_daily
date_keyFKINTEGER
product_keyFKINTEGER
warehouse_keyFKINTEGER
quantity_on_handINTEGER
Without a conformed dimension, the sales team might build its own product table calling tarps 'Shelter' while the warehouse team builds another calling them 'Accessories'. Then the 2 reports disagree about how big Shelter is, and no query can reconcile them.

Role-playing: one dimension, many jobs

fact_order_fulfillment carries a date key for each of its 3 milestones, from placed through delivered, and all 3 point at the same dim_date. Each join gives the table a different alias, and the alias is the role it plays in that query.

SELECT
placed.month_name AS placed_month,
shipped.day_of_week AS shipped_weekday,
COUNT(*) AS orders
FROM fact_order_fulfillment AS f
JOIN dim_date AS placed
ON f.placed_date_key = placed.date_key
JOIN dim_date AS shipped
ON f.shipped_date_key = shipped.date_key
GROUP BY placed.month_name, shipped.day_of_week

Orders that haven't shipped yet have no shipped date. If shipped_date_key is NULL on those rows, the inner join to shipped drops them from every count. Stars avoid this by pointing an empty milestone at a reserved dim_date row labeled 'Not yet', so unshipped orders stay in the result as their own group.

Degenerate: a key with no table

order_number 5001 is worth keeping: it groups the lines of one order and lets support look an order up. But the date has its own dimension, and so do the customer and the product, which leaves nothing to describe the order itself. A dimension table for it would hold one column. So the value stays in the fact table as a degenerate dimension: a dimension attribute with no dimension to join to.

Junk: a home for stray flags

Order lines also carry small flags: a yes-or-no for gift wrapping, plus the channel (web or app) and the payment method (card or wallet). 3 separate dimensions of 2 rows each would add 3 keys to every fact row. Left as text on the fact table, they widen hundreds of millions of rows. A junk dimension stores each combination that occurs as one row, and the fact row carries a single key.
order_profile_keyis_gift_wrappedchannelpayment_type
1NoWebCard
2NoWebWallet
3NoAppCard
4YesWebCard
With 2 values per flag the table tops out at 8 rows, however many orders arrive.
Multiple Choice

Fernhill starts recording a returns fact table. Each return row needs the product returned and the day it came back. Leadership wants return rate by category beside sales by category. What should the returns star use for products?

Every dimension type answers the same design question: where does this descriptive value live so that it is stored once, spelled the same everywhere, and one join from the numbers? A shared table, an alias, a column left on the fact row and a table of combinations are 4 answers to it.

Defining the Grain

Daily Life
Interviews

Order 5001 at Fernhill has 3 lines and one shipping fee of 6.00. A report on shipping income shows 18.00 for that order. Every stored value is the one the source sent, and the query is an ordinary SUM. The error was designed in when the table was built without anyone deciding what a single row stands for.

Grain is a sentence

The grain of a fact table is the meaning of exactly one row, stated in business words. For fact_order_line the sentence is: one row per product per order. The sentence is written before any column is chosen, because it decides both remaining design steps.

What the grain decides
  • Which dimensions fit. A dimension belongs only if it has a single value for each row. One order line has one product, one customer and one order date.
  • Which facts fit. A number belongs only if it is measured once per row. Quantity and line amount are. A fee charged once per order is not.
  • What the key is. The grain's dimensions form the composite key. For order lines that is order_number plus product_key, unique because Fernhill's cart merges a repeated product into one line with a higher quantity.

A fact at the wrong grain

Here is order 5001 with the shipping fee stored on every line.
order_numberproductquantitynet_amountshipping_fee
5001Ridge 2P Tent1249.006.00
5001Beam 400 Headlamp259.906.00
5001Trail Stove145.006.00

SUM(net_amount) returns 353.90, which is right, because each amount belongs to its line. SUM(shipping_fee) returns 18.00, 3 times the truth, because the fee belongs to the order and was copied to each line. Every query that sums the column inherits the error, and the size of the error depends on how many lines each order has, so no constant corrects it.

There are 2 honest repairs. Allocate the fee down to the grain, giving each line a share in proportion to its amount (4.22, 1.02 and 0.76), so the shares sum back to 6.00. Or keep the fee in a second fact table whose grain is one row per order. Both restate the fact at a grain where it's true once per row.

Choose the finest grain the source offers

A coarser grain is tempting because it's smaller. Fernhill could store one row per product per day: if the average product sells on 9 orders a day, its 9 order-line rows collapse into 1 and the table shrinks about 9x. But detail thrown away at load time can't be recovered by a query. Order lines add up to daily totals with a GROUP BY. Daily totals can never be split back into orders, so 'what is the average order value' becomes unanswerable.

TIP
Test a grain sentence by naming its key. If 2 rows could share every key column and still both be correct, the sentence is missing a word.
Fernhill's sales table grows upStep 1
>

Fernhill's first sales table was built for one dashboard and holds daily totals per product. 3 new requirements are about to test what one row of it can express. Pick how the model should change at each stage.

fact_daily_product_sales
date_keyINTEGERFKproduct_keyINTEGERFKunits_soldINTEGERnet_amountDECIMAL(12,2)

Marketing wants to know which products are bought in the same order, to design bundles. What do you do with the table?

The grain sentence is the contract of a fact table. Anyone who reads it knows what a COUNT(*) counts and which sums are safe. When a new requirement arrives, the first check is whether it fits the sentence, and if it does not, it gets a table with a sentence of its own.

Surrogate Keys

Daily Life
Interviews

Fernhill retires the Ridge 2P Tent and, a year later, reuses its SKU TNT-204 for a new ultralight model. If fact_order_line pointed at products by SKU, 3 years of old tent sales would now join to the new tent's name and weight and land in its category. The fact table is correct and every report built on it is wrong.

A key the warehouse owns

You met surrogate keys as one way to generate identity. In a star they are the rule: every dimension row gets an integer assigned by the warehouse's own load, and fact tables store only that integer. The source system's identifier, the business key, is kept on the dimension row as an ordinary attribute. It is used to match incoming data and never used to join.
customer_keysource_systemsource_customer_idcustomer_namecity
0nonenoneUnknown customerUnknown
7741web1001Ana RuizDenver
7742retail1001Tom BeckerLeeds

What the integer protects against

  • Reused identifiers. The source hands TNT-204 to a new product. When the Ridge tent was retired, its row 318 was marked inactive, and the lookup matches only active rows. The SKU finds no match, so the new tent gets key 9020. Old sales keep key 318, because fact rows are never re-keyed.
  • Colliding identifiers. The web store and the retail system both have a customer 1001. Keys 7741 and 7742 keep Ana and Tom apart.
  • Reformatted identifiers. A migration turns customer id 1001 into C-0001001. One attribute on one dimension row changes, and no fact row is touched.
  • Missing identifiers. A guest checkout has no customer id. The fact row points at key 0, the 'Unknown customer' row, so the foreign key is never NULL.

Without the unknown row, a NULL customer key would drop guest orders from any inner join to dim_customer, and revenue by city would quietly come up short. With key 0, those orders land in a visible 'Unknown' group and the total still matches.

Dimensions load before facts

The dimension loads first. For each incoming customer, the load looks up the pair of source_system and source_customer_id. A match reuses the existing key, and a new pair gets the next integer. The fact load then swaps every business key for its surrogate through that same lookup.

web and retail
Source systems
assign next integer
dim customer load
swap business keys
fact order line load
facts and dimensions
Star schema

Dimensions load first so the fact load can look up every surrogate key.

SELECT
COALESCE(c.customer_key, 0) AS customer_key,
s.order_number,
s.quantity,
s.net_amount
FROM staged_order_lines AS s
LEFT JOIN dim_customer AS c
ON s.source_system = c.source_system
AND s.customer_id = c.source_customer_id

The LEFT JOIN keeps every staged line, and COALESCE sends any line without a match to key 0. Row counts in and out stay equal as long as each pair appears once in the dimension, which is the check to run after every load.

The date dimension is the usual exception. Its key is often a readable integer such as 20260302, because the calendar will never reassign a day. Everywhere else, the price of a surrogate key is that lookup step in every fact load, plus keys that mean nothing to a person reading a raw fact row.
Multiple Choice

Fernhill buys a rival store and loads its orders. The rival's SKU LGT-011 is a lantern, while Fernhill's LGT-011 is the Beam 400 Headlamp. dim_product matches incoming rows on SKU alone. What happens to the rival's lantern sales?

A surrogate key separates 2 jobs that a source identifier tries to do at once. The business key says who the source thinks this is. The surrogate key says which dimension row a fact belongs to, and only the warehouse can change that.
PUTTING IT ALL TOGETHER

> A food delivery marketplace is building its first analytics model. Restaurants, couriers and customers each live in a separate operational system, and leadership wants order revenue, delivery times and courier availability on one dashboard.

The grain comes first: one row per menu item per order for revenue, stated before any column is chosen.
Revenue is a transaction fact, courier availability per hour is a periodic snapshot, and the order's progress from placed to picked up to delivered is an accumulating snapshot.
One conformed restaurant dimension and one date dimension, role-played as placed date and delivered date, let the 3 fact tables be compared in one report.
The order number stays on the fact row as a degenerate dimension, and a delivery fee charged once per order goes to an order-grain table.
Surrogate keys keep restaurant 88 from the menu system and restaurant 88 from the courier system on separate rows, with key 0 catching orders whose restaurant is missing.
KEY TAKEAWAYS
A star schema puts measurements in a central fact table and descriptions in dimensions, each one join away.
Fact tables come in 3 forms: transaction rows per event, periodic snapshots per interval, and accumulating rows per process.
Dimensions can be conformed or role-playing, or degenerate or junk, and each type decides where a descriptive value lives.
The grain is one sentence saying what a row means. Every dimension has to be true once per row, and so does every fact.
Surrogate keys assigned by the warehouse keep fact rows pointing at the right dimension row. They hold up when source identifiers are reused or collide, and they still work when a source identifier is missing.

Measurements in one central fact table, descriptions around it, and every analytical question takes the same shape.

Category
Data Modeling
Difficulty
intermediate
Duration
30 minutes
Challenges
12 hands-on challenges

Topics covered: The Star Schema, Types of Fact Tables, Types of Dimensions, Defining the Grain, Surrogate Keys

Lesson Sections

  1. The Star Schema (concepts: Star Schema, Snowflake Schema)

    Fernhill Outdoor sells camping gear online. Its order system is in 3NF, which keeps writes safe: each fact about a product or a customer lives in exactly one place. The cost shows up when an analyst asks for revenue by product category by month. One fact table, many dimensions A star schema sorts every column into one of 2 kinds of table. A fact table holds measurements of a business event: quantities and amounts you can add up. A dimension table holds the descriptions you filter and group by: t

  2. Types of Fact Tables (concepts: Fact Tables, Metric Additivity)

    Fernhill's operations team asks 3 questions in one week. How much did we sell yesterday? How much stock is in each warehouse right now? How long does an order take to reach the customer? Each one measures the business differently, and each needs a fact table with a different rhythm of rows. Transaction: one row per event That sparseness is why a transaction table struggles with the stock question. Stock on hand adds up every receipt since the warehouse opened and subtracts the sales, with return

  3. Types of Dimensions (concepts: Dimension Tables)

    Anatomy of a dimension row A dimension has one row per thing being described and one column per way of describing it. Hierarchies are flattened onto the row: a tent's subcategory and category sit beside its name. Codes are spelled out: the row says 'Shelter', never category 3, because the report will print whatever the column holds. The date dimension Conformed: one dimension, many stars Without a conformed dimension, the sales team might build its own product table calling tarps 'Shelter' while

  4. Defining the Grain (concepts: Grain Definition)

    Grain is a sentence A fact at the wrong grain Here is order 5001 with the shipping fee stored on every line. There are 2 honest repairs. Allocate the fee down to the grain, giving each line a share in proportion to its amount (4.22, 1.02 and 0.76), so the shares sum back to 6.00. Or keep the fee in a second fact table whose grain is one row per order. Both restate the fact at a grain where it's true once per row. Choose the finest grain the source offers

  5. Surrogate Keys (concepts: Surrogate Keys, Key Generation)

    A key the warehouse owns You met surrogate keys as one way to generate identity. In a star they are the rule: every dimension row gets an integer assigned by the warehouse's own load, and fact tables store only that integer. The source system's identifier, the business key, is kept on the dimension row as an ordinary attribute. It is used to match incoming data and never used to join. What the integer protects against Dimensions load before facts The date dimension is the usual exception. Its ke