The star schema

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

It is 9:10 on Monday. Tess has three dashboards that answer the same question, "weekend revenue in June". They say $3,103.21, $2,483.03 and $2,465.03. Each one was built on its own join of the shop's tables. Nora looks at the three and says: "One question needs one place to live."

You'll learn to

  • Design a star in four decisions: process, grain, dimensions, facts
  • Query a star, and fill its fact with key lookups
  • Put two fact tables side by side without counting twice
  • Explain how an engine runs a star join and stores its columns

Learn

Three dashboards, three answers

Look at what each dashboard did. One kept the cancelled lines: $3,103.21. One joined payments, where order 1005 has two rows, a capture and a refund, so its $18.00 line counted twice: $2,483.03. Only the third is right: $2,465.03. Each dashboard rebuilt the same joins its own way, and each way hid its own mistake.

The fix is one shape that every question uses. Put the events you measure, the order lines, in one long table in the middle. Put the tables that describe them around it: when, who, what. Drawn out, it looks like a star, so it is called a star schema.

The middle table is the fact table from Lesson 5.2. The points are its dimensions.

The fact_order_line table in the middle, with dim_date, dim_customer and dim_product around it; click a table to see its columns and its grain.

Click the fact first, then each point: every line between them is one key, which the fact stores and the dimension owns.

Four decisions, in this order

Nobody draws a star freehand. Kimball's method designs it in four decisions, and the order matters, because each one limits the next.

  1. The business process: what event do you measure? At SwiftKart: customers buying products.
  2. The grain: what does one row mean? One row per order line, the most detailed level the shop has. You can always add lines up into orders and days later. You can never split an order back into lines.
  3. The dimensions: what describes one line? When (dim_date), who (dim_customer), what (dim_product).
  4. The facts: the numbers measured on that line: qty, unit_price, line_amount.

Payments and page views are other processes. They get fact tables of their own.

Remember: process, grain, dimensions, facts, in that order. If you cannot say in one sentence what one row means, you are not ready to draw boxes.

A calendar, worked out once

The fact already holds the date, so why a dim_date table? Because people ask in business words: weekend, week of the year, month, public holiday, fiscal quarter. Working those out with date functions in every query is slow and easy to get wrong, and a holiday or a fiscal calendar cannot be computed at all.

So dim_date holds one row per calendar day, every label worked out once. Its key is the date as a number, 20250609: readable, and it sorts correctly. "Revenue at weekends" becomes one join and one filter.

Every dimension is built this way: one wide, flat table, one join from the fact. Splitting a dimension into a chain of smaller tables makes a snowflake schema.

The dashboards' question, the star way

SELECT d.is_weekend,
  COUNT(DISTINCT f.order_id) AS orders,
  SUM(f.line_amount) AS revenue
FROM fact_order_line f
JOIN dim_date d ON d.date_key = f.date_key
WHERE f.status <> 'cancelled'
GROUP BY d.is_weekend
ORDER BY d.is_weekend;

Every star query has this shape: the fact in FROM, one join per dimension on its key, filters and GROUP BY on dimension columns, sums on facts. The true row says $2,465.03, the one dashboard that was right.

Star or snowflake?

Star schemaSnowflake schema
Each dimension is one wide table: dimproduct holds category as a columnDimensions are split into more tables: dimproduct points to dimcategory
One join from the fact to any attributeTwo or more joins to reach some attributes
Repeats some text (the category name on every product)Stores each label once
Simple and fast for BI tools and for peopleSaves a little space; more joins, more ways to get them wrong
The default in most warehousesUsed when a dimension is huge or a sub-table is shared

Filling the fact: swap every key

Now fill the fact from Dana's tables in the shop's database. Each fact row starts as one row of order_items, because that is the grain. Then four small jobs:

  • take qty and unit_price from the line, and multiply them for line_amount;
  • take the order's date, customer and status from orders;
  • turn the date into date_key;
  • swap each natural key (the shop's own id, such as product_id 103) for the surrogate key its dimension gave it (Lesson 5.1).

The product swap is a plain join. The customer swap needs the date as well, because one customer can have several versions. Lesson 5.4 shows why.

From the shop's tables to one fact row

The shop's order_items and orders tables on the left feed three key lookups in the middle, the date key, dim_product and dim_customer, which feed fact_order_line on the right.

Follow the arrows left to right: the blue tables carry the shop's own ids, the violet lookups swap them for warehouse keys, and only keys and numbers reach the green fact.

Fact rows from the source

SELECT
  i.order_id,
  i.line_no,
  TO_CHAR(o.order_ts, 'YYYYMMDD')::INT AS date_key,
  o.customer_id,
  i.product_id,
  o.status,
  i.qty,
  i.unit_price,
  i.qty * i.unit_price AS line_amount
FROM order_items i
JOIN orders o ON o.order_id = i.order_id
ORDER BY i.order_id, i.line_no;

TO_CHAR(order_ts, 'YYYYMMDD')::INT turns a timestamp into the integer date key. This is the first half of the load: the rows still carry the natural keys customer_id and product_id. In the practice you add the product swap.

One customer table for every fact

SwiftKart will soon have more fact tables: fact_payment (one row per payment attempt) and fact_page_view (one row per page view). If each fact had its own customer table with its own keys, "revenue per customer" and "visits per customer" would never line up.

So every fact shares one dim_customer: the same keys, the same labels, the same meaning. A dimension shared like this is a conformed dimension.

Now you can put two processes side by side. Sum each fact to the same grain first, say one row per customer. Then join the two summaries. This is called drilling across.

Drill across two facts

WITH sales AS (
  SELECT c.customer_id, SUM(f.line_amount) AS revenue
  FROM fact_order_line f
  JOIN dim_customer c ON c.customer_key = f.customer_key
  GROUP BY c.customer_id
),
visits AS (
  SELECT c.customer_id, COUNT(*) AS page_views
  FROM fact_page_view v
  JOIN dim_customer c ON c.customer_key = v.customer_key
  GROUP BY c.customer_id
)
SELECT v.customer_id, v.page_views, COALESCE(s.revenue, 0) AS revenue
FROM visits v
LEFT JOIN sales s ON s.customer_id = v.customer_id
ORDER BY v.customer_id;

fact_page_view (made for this card) shares dim_customer and dim_date with fact_order_line. Each CTE sums one fact to one row per customer, so the last join is one to one. Customer 30 browsed but never bought: revenue 0.

The trap: never join two fact tables row to row. fact_order_line JOIN fact_page_view ON customer_key pairs every line with every view of that customer, so revenue and views both multiply: Lesson 5.1's fan-out again. Sum each fact to a shared grain first, then join the summaries.

Under the hood: short tables first

How does an engine run a star query? Look at the sizes: the fact is long, the dimensions are short.

So the engine reads each short table first, keeps the rows that pass its filter, and puts them in a hash table: a lookup from a key to a row, like the contacts list on a phone. This is the build side.

Then it reads the long fact once, start to end, and each line looks up its keys. This is the probe side: one pass, no sorting.

Weekend revenue by category, through the star

The engine builds lookups from dim_date and dim_product, streams the 201 fact lines once, drops weekday and cancelled lines, looks up each line's category and adds 45 lines up to 2,465.03 dollars.

  1. Build the lookups. The engine reads dim_date (30 rows) and keeps the 9 weekend days. It reads all 20 rows of dim_product. Both go into hash tables in memory, from a key to what the query needs.

  2. Stream the fact once. The engine reads the 201 lines from start to end. Each line checks its own status and looks up its date_key in the weekend table. 141 lines fall on a weekday, 15 more were cancelled, and 45 go on.

  3. Look up the category. Each of the 45 lines finds its product_key in the product table and picks up its category. Still one pass, and still no sorting.

  4. Add up by category. The sums grow as the lines arrive: Sports $818.70, Fashion $671.60, Electronics $364.87, and four smaller categories. Together they make $2,465.03, the right dashboard's number.

Watch the fact box: the short tables are read once into memory, and the long table is read once, start to end, with no sort anywhere.

At SwiftKart's real size the plan is the same. Picture a year: 730M fact rows, 365 dates, 50,000 products and 20M customers (round numbers for the example).

In Spark this join is a BroadcastHashJoin. A dimension estimated under spark.sql.autoBroadcastJoinThreshold, 10 MB by default, is copied to every executor, so the 730M fact rows never cross the network. A bigger dimension, such as 20M customers, gets a sort-merge join instead: both sides are shuffled by the key, the fact included. Small integer surrogate keys keep the hash tables small; long text keys cost memory and comparisons.

One more trick shows in the plan. Dynamic partition pruning runs the dim_date filter first and hands the matching keys to the fact scan, so whole days of the fact are never read.

Weekend revenue by category: the physical plan

A Spark plan tree: a final aggregate over an exchange over a partial aggregate over two broadcast hash joins; the fact scan uses a dynamic pruning filter and reads 104 of 365 date partitions, and each dimension arrives through a broadcast exchange.

Read it bottom up: the violet branches are the build sides, the green scan is the probe side, and only the amber step shuffles, one partial sum per category per task. 2025 has 104 weekend days, so the scan reads 104 of 365 daily partitions, about 208M of 730M rows.

Where the rows live on a warehouse

On Redshift and Synapse dedicated pools, data lives on the compute nodes, so where each row sits decides what a join costs. Redshift splits each node into slices, each with its share of the node's memory and disk, and offers four distribution styles:

  • KEY: equal values of one column go to the same slice;
  • ALL: a full copy of the table on every node;
  • EVEN: rows dealt out round-robin;
  • AUTO, the default: a small table starts as ALL, then moves to KEY or EVEN as it grows.

Put the fact and its biggest dimension on the same key, customer_key, and their join moves nothing: EXPLAIN shows DS_DIST_NONE. Otherwise you see DS_BCAST_INNER (the whole inner table copied to every node) or DS_DIST_BOTH (both sides moved), which AWS calls "not good".

A star on two Redshift nodes

A leader node beside two compute nodes with two slices each; every slice holds the fact rows and dim_customer rows for the same customer keys, plus a full copy of the small dim_date.

Read each slice as a small warehouse of its own: its fact rows and its customers share keys, so it joins them without asking another node. ALL multiplies storage and load time by the node count, so AWS keeps it for small tables that change slowly.

Few distinct values, few bits

Now the bytes on disk. Parquet, and every warehouse format like it, stores a column with dictionary encoding: each distinct value once, then each row as a small number pointing into that list. Think of a cafe order slip that says "dish 3" instead of the dish's full name.

Each pointer takes ceil(log2(distinct values)) bits, packed tight: bit-packing. Runs of the same pointer shrink again with run-length encoding. So status (5 values) costs 3 bits a row, country (200) 8 bits, city (10,000) 14 bits.

A column of unique values gains nothing. Its dictionary grows too big, the writer falls back to plain encoding, and order_id costs its full 8 bytes a row. Sorting helps twice: runs get longer, and each block's min/max range gets narrower, so more blocks are skipped.

One column on 100 million rows, encoded

Bars compare one column on 100 million rows after dictionary encoding and bit-packing: 37.5 MB for status, 75 MB for category, 100 MB for country, 175 MB for city, against 800 MB for a unique order id stored plain.

Each bar is bits a row × 100M ÷ 8, before run-length encoding and the codec (Snappy or ZSTD), which shrink the green bars much further once the data is sorted. That is why Lesson 5.5 can copy labels onto the fact almost for free.

One Parquet column chunk encoded with a dictionary: the distinct values stored once, each row an index, and runs of equal indexes collapsed by run-length encoding.

Step through status unsorted, then sorted: the same 5 values take far fewer bytes once equal values sit together.

Numbers to remember

WhatThe numberWhy it matters
Broadcast limitspark.sql.autoBroadcastJoinThreshold = 10 MBA dimension estimated under it is copied to every executor. Over it, a sort-merge join shuffles the fact too
Dynamic partition pruningspark.sql.optimizer.dynamicPartitionPruning.enabled = true (Spark 3.0+)A filter on dimdate prunes the fact's date partitions: 104 of 365 for weekends in 2025. The fact must be partitioned on the join key
Redshift distributionKEY, ALL, EVEN, AUTO (the default)DSDISTNONE moves nothing; DSBCASTINNER and DSDISTBOTH move data on every run. Snowflake, BigQuery and Databricks have no distribution key: they pick broadcast or shuffle per query
Delta statisticsmin/max on the first 32 columns, by defaultFiles are skipped only on columns that have statistics
Snowflake micro-partitions50 to 500 MB of uncompressed data eachEach keeps every column's value range and distinct count, for skipping
ClusteringBigQuery: up to 4 clustering columnsPartition or cluster the fact by date first, then by the next most-filtered column. Databricks uses liquid clustering
Dictionary bit widthceil(log2(distinct values)) bits a row5 values: 3 bits; 200: 8 bits; 10,000: 14 bits. Unique values fall back to plain: 8 bytes for a BIGINT
Namesdim and fct tablesPower BI's own guidance recommends a star; dbt projects keep dimcustomers and fctorders in a marts folder. The snowflake schema has nothing to do with Snowflake, the cloud warehouse

What changed at SwiftKart

The three dashboards now read one star: fact_order_line in the middle, dim_date, dim_customer and dim_product around it. Tess deletes two of them. Weekend revenue says $2,465.03 wherever she asks, because every query has the same shape: filter the dimensions, join on their keys, add up the facts.

You also have a rule for the next fact tables. Payments and page views get stars of their own that share the same conformed dimensions, and two facts meet only after each is summed to a shared grain.

One point of the star is less still than it looks. Customers move, and the app overwrites their city. Lesson 5.4 asks what the warehouse should remember when that happens.

In one line

A star schema is one fact table joined to its dimensions: filter the dimensions, join on their keys, add up the facts, and never join two facts row to row.

Interview corner

Walk me through designing a star schema for an online shop.

I pick the process (sales), declare the grain (one row per order line), choose the dimensions (date, customer, product, maybe promotion) and then the facts measured at that grain (quantity, unit price, line amount). Dimensions get surrogate keys, the fact stores those keys plus the measures, and I add a date dimension for calendar attributes. Then I say how the customer dimension keeps history.

Star schema or snowflake schema?

In a star, each dimension is one denormalised table, so any attribute is one join from the fact. A snowflake normalises dimensions into sub-tables, saving a little space at the cost of more joins. I default to a star because it is simpler and faster for BI tools; I snowflake only when a dimension is very large or a sub-table is shared by many dimensions.

A star query on a Spark lakehouse takes 6 minutes and the plan shows a SortMergeJoin with an Exchange on the 730-million-row fact. What do you check?

A sort-merge join means a dimension was estimated above spark.sql.autoBroadcastJoinThreshold (10 MB by default), so Spark shuffled the fact to join it. I check which dimension and its real size after filters: a 50,000-row product table should broadcast, and stale or missing statistics can hide that. If it is a 20-million-row customer dimension, I filter or project it before the join, raise the threshold only if executors have the memory, or serve that dashboard from a wide table. I also check that the fact scan shows partition filters, ideally from dynamic partition pruning on date_key.

Why is copying a category name onto every fact row cheap in Snowflake or Parquet but expensive in Postgres?

A column store keeps each column separately and dictionary-encodes it: the 50 category names are stored once per chunk and each row holds a 6-bit index, which run-length encoding shrinks further when the data is sorted. A row store writes the full text into every row, so 730 million rows times 12 bytes is about 8.8 GB, and every scan reads it whether the query needs it or not. That asymmetry is why warehouses denormalise freely and OLTP databases normalise.