Worked example

Star schema example: model orders without double-counting revenue.

Join orders to their lines, sum the order total, and revenue comes out too high by however many lines each order has. This example models one small fictional shop as a star schema, shows the inflated number next to the correct one, and explains the design decisions behind each table.

Facts, dimensions, keys and grain in plain terms

A star schema splits reporting data into two kinds of table. A fact table records things that happened, one row per event, with the numbers you add up: quantities, amounts, fees. A dimension table describes the things those events are about, such as customers and products, with the attributes people group and filter by. Each fact row points at one row in each dimension, and drawn out, the facts sit in the middle with the dimensions around them.

The grain is the sentence that says what one row is: one row per order line, one row per order, one row per customer. A key is the column, or set of columns, that is unique at that grain. Declaring both before writing SQL is most of the design, because every measure has a grain of its own. A line amount belongs to one line. An order total and a shipping fee belong to the whole order.

That is why an order total cannot simply be repeated on each line and summed. Joining a three-line order to its lines gives three rows, each carrying the same total, and the sum counts the order three times. The fix is not a cleverer SUM: it is putting each measure in a table whose grain matches it.

  • Fact: a table of events at one declared grain, holding additive measures and the keys of the dimensions it belongs to.
  • Dimension: one row per thing described, identified by a key, holding the attributes reports group and filter by.
  • Grain: what one row of a table represents, said in one sentence.
  • Key: the column or columns that identify exactly one row at that grain.

The star schema in one picture

Two facts and two dimensions. Each fact row points at exactly one customer and, for lines, exactly one product. Every join in the reports runs from a fact to a dimension, many rows to one, which is why no measure is ever repeated.

Dimension

dim_customer

Grain: one row per customer, plus one unknown row

  • customer_keykey
  • customer_name
  • segment
  • country

Fact

fct_order_line

Grain: one row per order line

  • order_idkey
  • line_numberkey
  • order_date
  • customer_keyjoins dim_customer
  • source_customer_id
  • product_keyjoins dim_product
  • quantitymeasure
  • line_amountrevenue

Dimension

dim_product

Grain: one row per product

  • product_keykey
  • product_name
  • category

Fact

fct_order

Grain: one row per order

  • order_idkey
  • order_date
  • customer_keyjoins dim_customer
  • shipping_feemeasure
The tables the script creates. A key identifies one row at the table’s grain; fct_order_line needs order_id and line_number together. Revenue is on the line fact, shipping on the order fact.

The worked example, step by step

Fictional data, not a real shop. The customers, products and orders are invented to show the method. Run the script as it is first and check each result against the expected output under it, then replace the four source tables with your own.

One BigQuery Standard SQL script: the eight blocks below, in order, with the expected outputs as comments. All the data is inline. It reads none of your tables and creates only temporary tables. No sign-up needed.

1. The fictional shop’s source tables

Four tables, as a shop’s order system might hold them: three customers, three products, four orders and seven order lines. Each order stores its own total and a shipping fee; each line stores a product, a quantity and a unit price. The order total is the sum of the order’s lines, before shipping.

Two details are planted on purpose. Order O-1004 belongs to customer C004, whose customer record has not been loaded yet. Customer C003 has never ordered. Amounts are NUMERIC literals, which BigQuery stores as exact decimals, so no total in this script carries a floating-point rounding error.

BigQuery Standard SQL
-- Star schema example: model orders without double-counting revenue.
-- BigQuery Standard SQL. https://lp-data.cloud/insights/star-schema-example
--
-- FICTIONAL DATA: the shop, its customers, products and orders are invented to
-- show the method. They are not from any client or real system. Run the whole
-- script as it is first and check every result against the expected output
-- written under it.
--
-- It reads none of your tables and changes nothing: everything it creates is
-- a temporary table that disappears when the script ends. In the console, use
-- Run (not Run selection) and open each result from the list of statements.
--
-- "Revenue" here means the value of products sold, before shipping, in one
-- currency. It is not recognised revenue, and there are no refunds or tax.

CREATE TEMP TABLE src_customers AS
SELECT * FROM UNNEST([
  STRUCT('C001' AS customer_id, 'Ana Silva' AS customer_name, 'Retail' AS segment, 'PT' AS country),
  ('C002', 'Ben Carter', 'Trade', 'GB'),
  ('C003', 'Chloé Martin', 'Retail', 'FR')  -- has no orders
]);

CREATE TEMP TABLE src_products AS
SELECT * FROM UNNEST([
  STRUCT('P01' AS product_id, 'Ceramic mug' AS product_name, 'Kitchen' AS category),
  ('P02', 'Linen tea towel', 'Kitchen'),
  ('P03', 'A5 notebook', 'Stationery')
]);

-- One row per order. order_total is the sum of the order's lines.
CREATE TEMP TABLE src_orders AS
SELECT * FROM UNNEST([
  STRUCT('O-1001' AS order_id, 'C001' AS customer_id, DATE '2026-10-01' AS order_date,
         NUMERIC '46.35' AS order_total, NUMERIC '4.90' AS shipping_fee),
  ('O-1002', 'C002', DATE '2026-10-02', NUMERIC '110.00', NUMERIC '0.00'),
  ('O-1003', 'C001', DATE '2026-10-05', NUMERIC '21.70', NUMERIC '4.90'),
  ('O-1004', 'C004', DATE '2026-10-06', NUMERIC '12.50', NUMERIC '4.90')  -- C004 not loaded yet
]);

-- One row per order line.
CREATE TEMP TABLE src_order_lines AS
SELECT * FROM UNNEST([
  STRUCT('O-1001' AS order_id, 1 AS line_number, 'P01' AS product_id, 2 AS quantity, NUMERIC '12.50' AS unit_price),
  ('O-1001', 2, 'P02', 1, NUMERIC '8.75'),
  ('O-1001', 3, 'P03', 3, NUMERIC '4.20'),
  ('O-1002', 1, 'P01', 10, NUMERIC '11.00'),
  ('O-1003', 1, 'P03', 1, NUMERIC '4.20'),
  ('O-1003', 2, 'P02', 2, NUMERIC '8.75'),
  ('O-1004', 1, 'P01', 1, NUMERIC '12.50')
]);

2. The mistake: join orders to lines, then sum the order total

This is the query a flat orders-and-lines extract invites. Joining orders to their lines is correct, and each line gets its order’s customer and date. But it also gets the order’s total, once per line. Sum that column and O-1001, with three lines, is counted three times.

Result 1 shows it order by order. Across the four orders the true total is 190.55; the joined sum is 304.95, overstated by 114.40. Nothing errors and nothing looks broken: the inflation is exactly the size of how many lines each order happens to have.

BigQuery Standard SQL
-- Result 1: each order's total, summed after joining to its lines.
SELECT
  o.order_id,
  COUNT(*) AS line_rows,
  ANY_VALUE(o.order_total) AS order_total,
  SUM(o.order_total) AS summed_after_join
FROM src_orders AS o
JOIN src_order_lines AS l ON l.order_id = o.order_id
GROUP BY o.order_id
ORDER BY o.order_id;
-- Expected with the fictional data:
-- order_id | line_rows | order_total | summed_after_join
-- O-1001   | 3         | 46.35       | 139.05
-- O-1002   | 1         | 110         | 110
-- O-1003   | 2         | 21.7        | 43.4
-- O-1004   | 1         | 12.5        | 12.5
Expected output with the fictional data
order_idline_rowsorder_totalsummed_after_join
O-1001346.35139.05
O-10021110110
O-1003221.743.4
O-1004112.512.5

3. The same mistake, reported by product

Grouping the joined rows by product makes it worse, because the number no longer means anything at all. Each product is credited with the whole value of every order that contained it. The tea towel and the notebook both show 68.05, although they sold 26.25 and 16.80.

COUNT(DISTINCT order_id) would give the right number of orders here, which is what makes this easy to miss: the counts look right while the amounts are wrong.

BigQuery Standard SQL
-- Result 2: "revenue by product" from the joined rows. Wrong on every row.
SELECT
  l.product_id,
  COUNT(DISTINCT o.order_id) AS orders,
  SUM(o.order_total) AS naive_revenue
FROM src_orders AS o
JOIN src_order_lines AS l ON l.order_id = o.order_id
GROUP BY l.product_id
ORDER BY l.product_id;
-- Expected with the fictional data:
-- product_id | orders | naive_revenue
-- P01        | 3      | 168.85
-- P02        | 2      | 68.05
-- P03        | 2      | 68.05
Expected output with the fictional data
product_idordersnaive_revenue
P013168.85
P02268.05
P03268.05

4. Build the customer and product dimensions

A dimension has one row per thing it describes, and its key says which thing. Here the keys are the shop’s own IDs, renamed customer_key and product_key so it is clear which column the facts join on.

dim_customer gets one extra row: an Unknown customer. A fact whose customer is not in the table yet points at it, so its revenue stays in every total and shows up as a named row instead of disappearing from an inner join. These are current attributes: one row per customer, as the customer is today.

BigQuery Standard SQL
-- Grain: one row per customer, plus one Unknown row. Key: customer_key.
-- Current attributes only: a customer who changes segment changes everywhere.
CREATE TEMP TABLE dim_customer AS
SELECT customer_id AS customer_key, customer_name, segment, country
FROM src_customers
UNION ALL
SELECT 'UNKNOWN', 'Unknown customer', 'Unknown', 'Unknown';

-- Grain: one row per product. Key: product_key.
CREATE TEMP TABLE dim_product AS
SELECT product_id AS product_key, product_name, category
FROM src_products;

5. Build one fact per grain

fct_order_line has one row per order line, identified by order_id and line_number together. Its revenue measure is line_amount, quantity times unit price, which belongs to the line and adds up correctly across customers, products and dates. Joining lines to orders is safe in this direction: each line has exactly one order, so the order’s customer and date come down without multiplying anything.

The shipping fee is charged once per order, so it does not go on the line. It goes on fct_order, with one row per order. The order total is not stored on either: it is the sum of the lines, and the first ASSERT below fails the script if a source total ever disagrees with its lines. The other two fail it if either fact has more than one row for its key.

BigQuery Standard SQL
-- Grain: one row per order line. Key: (order_id, line_number).
-- Measures: quantity and line_amount, both additive across every dimension.
CREATE TEMP TABLE fct_order_line AS
SELECT
  l.order_id,
  l.line_number,
  o.order_date,
  IF(c.customer_id IS NULL, 'UNKNOWN', o.customer_id) AS customer_key,
  o.customer_id AS source_customer_id,  -- kept, so the line can be re-keyed later
  l.product_id AS product_key,
  l.quantity,
  l.quantity * l.unit_price AS line_amount
FROM src_order_lines AS l
JOIN src_orders AS o ON o.order_id = l.order_id
LEFT JOIN src_customers AS c ON c.customer_id = o.customer_id;

-- Grain: one row per order. Key: order_id.
-- Measures recorded once per order live here, never on the line.
CREATE TEMP TABLE fct_order AS
SELECT
  o.order_id,
  o.order_date,
  IF(c.customer_id IS NULL, 'UNKNOWN', o.customer_id) AS customer_key,
  o.shipping_fee
FROM src_orders AS o
LEFT JOIN src_customers AS c ON c.customer_id = o.customer_id;

ASSERT NOT EXISTS (
  SELECT 1
  FROM src_orders AS o
  LEFT JOIN (SELECT order_id, SUM(line_amount) AS lines_total FROM fct_order_line GROUP BY order_id) AS f
    ON f.order_id = o.order_id
  WHERE f.lines_total IS DISTINCT FROM o.order_total
) AS 'An order total does not equal the sum of its lines';

ASSERT NOT EXISTS (
  SELECT 1 FROM fct_order_line GROUP BY order_id, line_number HAVING COUNT(*) > 1
) AS 'fct_order_line has more than one row for an order line';

ASSERT NOT EXISTS (
  SELECT 1 FROM fct_order GROUP BY order_id HAVING COUNT(*) > 1
) AS 'fct_order has more than one row for an order';

6. Revenue by customer, from the star

Start from the dimension and left join the fact, so every customer appears whether or not they ordered. Ana’s two orders total 68.05. Chloé shows 0 with no orders: she exists, and there are no facts for her. The Unknown customer shows 12.50 from one order: there is a fact, and the customer it belongs to is not in the dimension yet. Those are two different situations, and the table keeps them apart.

BigQuery Standard SQL
-- Result 3: revenue by customer. Sums to 190.55.
SELECT
  c.customer_key,
  c.customer_name,
  c.segment,
  COUNT(DISTINCT f.order_id) AS orders,
  COALESCE(SUM(f.line_amount), 0) AS revenue
FROM dim_customer AS c
LEFT JOIN fct_order_line AS f ON f.customer_key = c.customer_key
GROUP BY c.customer_key, c.customer_name, c.segment
ORDER BY c.customer_key;
-- Expected with the fictional data:
-- customer_key | customer_name    | segment | orders | revenue
-- C001         | Ana Silva        | Retail  | 2      | 68.05
-- C002         | Ben Carter       | Trade   | 1      | 110
-- C003         | Chloé Martin     | Retail  | 0      | 0
-- UNKNOWN      | Unknown customer | Unknown | 1      | 12.5
Expected output with the fictional data
customer_keycustomer_namesegmentordersrevenue
C001Ana SilvaRetail268.05
C002Ben CarterTrade1110
C003Chloé MartinRetail00
UNKNOWNUnknown customerUnknown112.5

7. Revenue by product, from the star

The same fact, grouped by the other dimension. Each line counts once, under its own product, so the rows add up to the same 190.55. Compare it with Result 2: the mug sold 147.50, not 168.85, and the tea towel and notebook are no longer the same number.

BigQuery Standard SQL
-- Result 4: revenue by product. Sums to 190.55.
SELECT
  p.product_key,
  p.product_name,
  p.category,
  SUM(f.quantity) AS units,
  SUM(f.line_amount) AS revenue
FROM fct_order_line AS f
JOIN dim_product AS p ON p.product_key = f.product_key
GROUP BY p.product_key, p.product_name, p.category
ORDER BY p.product_key;
-- Expected with the fictional data:
-- product_key | product_name    | category   | units | revenue
-- P01         | Ceramic mug     | Kitchen    | 13    | 147.5
-- P02         | Linen tea towel | Kitchen    | 3     | 26.25
-- P03         | A5 notebook     | Stationery | 4     | 16.8
Expected output with the fictional data
product_keyproduct_namecategoryunitsrevenue
P01Ceramic mugKitchen13147.5
P02Linen tea towelKitchen326.25
P03A5 notebookStationery416.8

8. The totals, side by side

The last result puts the two designs next to each other. Revenue from the joined rows is 304.95; from the line fact it is 190.55, which matches the four order totals. Shipping summed from the joined rows is 29.40, double the 14.70 actually charged, because the same thing happens to every measure recorded once per order.

BigQuery Standard SQL
-- Result 5: each measure from the joined rows and from its own fact.
SELECT
  'Revenue' AS measure,
  (SELECT SUM(o.order_total) FROM src_orders AS o JOIN src_order_lines AS l ON l.order_id = o.order_id) AS joined_rows,
  (SELECT SUM(line_amount) FROM fct_order_line) AS star_schema
UNION ALL
SELECT
  'Shipping',
  (SELECT SUM(o.shipping_fee) FROM src_orders AS o JOIN src_order_lines AS l ON l.order_id = o.order_id),
  (SELECT SUM(shipping_fee) FROM fct_order)
ORDER BY measure;
-- Expected with the fictional data:
-- measure  | joined_rows | star_schema
-- Revenue  | 304.95      | 190.55
-- Shipping | 29.4        | 14.7
Expected output with the fictional data
measurejoined_rowsstar_schema
Revenue304.95190.55
Shipping29.414.7

The BigQuery console shows NUMERIC values without trailing zeros, so 110.00 appears as 110 and 14.70 as 14.7. Other clients may print two decimals; the values are the same.

Orders with several lines: give each measure its own grain

Most order data arrives at two grains at once. Products, quantities and prices are recorded per line; totals, shipping, discount codes and payment details are recorded per order. Model the line as the main fact, because that is the finest grain the questions need, and derive the order total from the lines instead of storing a second copy that can drift from them.

Measures that only exist per order get their own fact at order grain, as shipping_fee does in fct_order. Reports that need both join each fact to the shared dimensions separately and combine the aggregated results, never the raw rows. If someone needs shipping per product, that needs an allocation rule, such as by line value or by weight, agreed with whoever owns the number and written down. Do not reach for SUM(DISTINCT order_total) either: two different orders with the same total collapse into one value.

An unknown customer is not a missing order

Two gaps look alike in a report and mean opposite things. An unknown dimension member is a fact whose key has no match: order O-1004 happened and was paid for, but customer C004 has not reached the customer table. Point it at an explicit Unknown row, keep the source ID next to it, and the revenue stays in every total while the gap stays visible and fixable. An inner join to the dimension would quietly drop the order instead.

A missing fact is a dimension member with nothing recorded: Chloé is a real customer who has not ordered. Starting the query from the dimension and left joining the fact shows her with zero, which is correct. If an expected fact is missing because a load failed, no join can tell you; that needs a completeness or reconciliation check against the source.

Current attributes, and what they cannot tell you

This example keeps current attributes only: dim_customer has one row per customer, as the customer is today. That is the right default for most questions and the easiest to keep correct. Its limitation is history. If Ben moved from Retail to Trade last month, every past order of his now reports under Trade, and last quarter’s revenue by segment changes when you rerun it.

When the business needs results as they were at the time, the dimension has to keep versions, each with its own surrogate key and validity dates, and each fact has to point at the version valid on its order date. That is a slowly changing dimension. It is deliberately not built here; decide whether you need it before you build one, because it changes every join.

When a flat reporting table is enough

A star schema is not always the answer. If one team asks a handful of questions of one process at one grain, a single wide table at order-line grain, with the customer and product attributes already joined on, is simpler to use and perfectly correct, provided every measure on it belongs to that grain. The double-counting in this example comes from mixing grains in one table, not from flattening.

Move to shared dimensions when several facts need the same customer or product attributes, when those attributes change and must change everywhere at once, or when measures at different grains have to be reported side by side. Fill in the worksheet below for your own process first; it usually shows which of the two you need.

Worksheet: design your own fact table

Fill this in for one business process before writing any SQL, and agree it with the person who owns the numbers. If you cannot finish the grain line in one sentence, that is the first thing to resolve.

  1. Business questions

    Which three to five questions must the model answer, in the words of the person asking?

    In the example: revenue by customer, revenue by product, shipping charged.

  2. Fact grain

    One row in the fact table is one … what? Write it as one sentence the business owner agrees with.

    In the example: one row per order line.

  3. Fact key

    Which column or columns are unique at that grain?

    In the example: order_id and line_number together.

  4. Dimensions

    Which things do people group and filter by? For each, its key and the attributes it carries.

    In the example: dim_customer on customer_key, dim_product on product_key.

  5. Measures at this grain

    Which numbers belong to one fact row, and can each be summed across every dimension?

    In the example: quantity and line_amount, both fully additive.

  6. Measures at another grain

    Which numbers are recorded once per order, account or day, and where will they live instead?

    In the example: shipping_fee, on fct_order with one row per order.

  7. Unknown members

    What does a fact get when its dimension key has no match yet, and who fixes it?

    In the example: the UNKNOWN customer, with the source ID kept for re-keying.

  8. History

    Should past facts report under today’s attributes, or as they were at the time?

    In the example: today’s attributes only.

Questions

Related questions

Why does revenue double when I join orders to order lines?

Because the join returns one row per line, and an order-level value such as the order total or shipping fee is repeated on each of them. Summing it counts each order once per line. Sum line amounts from a line-grain fact instead, and keep order-level measures in a table with one row per order.

Can SUM(DISTINCT order_total) fix the double-counting?

No. It removes repeats of the same value, not of the same order, so two different orders with the same total are counted once. It also hides the design problem. Aggregate each measure at its own grain before combining.

What is the grain of a fact table?

What one row represents, stated in one sentence, such as one row per order line. Every measure on the table must belong to that grain, and the key, for example order_id and line_number together, must be unique at it.

Should a star schema use surrogate keys?

Not necessarily for current-state dimensions, where the source ID is unique and stable, as in this example. Surrogate keys become necessary when a dimension keeps history, because one customer then has several rows and each needs its own key.

Does the script need access to my data?

No. All the fictional data is inline in the script, which creates only temporary tables, reads none of your tables and changes nothing. Nothing is sent to this site. To model your own data you replace the four source tables with SELECTs from yours, in your own BigQuery project.

The Divergence Point — monthly

Where the numbers stop agreeing, and what to do about it. One email a month on data quality, reconciliation and building warehouses that survive contact with a real business. No recycled LinkedIn posts.

Tell me what is broken.

A short call is usually enough to tell whether this is a two-week fix or a two-month one — and whether I am the right person for it.