SQL Dojo
Modeling

Star schema: fact and dimension tables

Fact tables at a stated grain, joined many to one to dimension tables, so a measure gives the same total however a report slices it.

A star schema is how most warehouses lay out data for reporting. A fact table records what happened, at a grain stated first ("one row per order line"), with its measures and the keys of its dimensions. Each dimension table holds one row per customer, product or day, with the attributes reports filter and group by.

SELECT c.country, p.category, SUM(f.amount) AS revenue
FROM fct_sales f                                          -- one row per order line
JOIN dim_customer c ON c.customer_key = f.customer_key   -- many to one
JOIN dim_product  p ON p.product_key  = f.product_key    -- many to one
GROUP BY c.country, p.category;

Kimball's four kinds of fact table: transaction (an order line), periodic snapshot (a balance per account and month), accumulating snapshot (one row per order, updated at each milestone), factless (rows to count).

The trap. A join that is not many to one repeats fact rows: a dimension with two rows for a key, or a "dimension" on the many side, such as the payments of an order. Every sum grows, with no error. For an attribute with several values (an order paid by gift card and card), use a bridge table whose weights sum to 1 per fact.

On your warehouse. Snowflake, BigQuery, Databricks and Redshift accept primary and foreign keys but do not enforce them, so a duplicate dimension key gets in silently: test each key (unique, not null, every fact key found in its dimension).

SELECT c.country,
       COUNT(*) AS order_lines,
       SUM(l.quantity * l.unit_price) AS revenue
FROM order_lines l                                  -- the fact: one row per order line
JOIN orders o    ON o.order_id = l.order_id         -- its order's date and status
JOIN customers c ON c.customer_id = o.customer_id   -- many lines, one customer
WHERE o.status <> 'cancelled'
  AND o.ordered_at >= DATE '2025-01-01' AND o.ordered_at < DATE '2026-01-01'
GROUP BY c.country
ORDER BY revenue DESC;
countryorder_linesrevenue
France159949891.40
Switzerland2427366.90
Germany1535559.30
Belgium1574812.90
Luxembourg1324487.10
Spain1333767.00
Italy1153049.80
Try it in Randori