Analysts ask questions such as "revenue by month and product category". A star schema is a way of laying out tables so that these questions are easy to write and fast to run.
Facts and dimensions
A fact table records events you can measure: an order line, a page view, a payment. Each row holds numbers (quantity, amount) and keys that point to the context.
A dimension table describes that context: who, what, where, when. A product dimension has name, category and brand. A date dimension has day, month, quarter and whether it is a holiday. Drawn on paper, the fact table sits in the middle and the dimensions radiate out like the points of a star.
Decide the grain first
The grain is what one row of the fact table means. "One row per order line" is a grain. Everything in the table must be true at that level. Mixing grains, such as order totals next to line prices, produces numbers that silently double count.
An example
CREATE TABLE dim_product (product_key serial PRIMARY KEY, name text, category text);
CREATE TABLE dim_date (date_key int PRIMARY KEY, day date, month int, year int);
CREATE TABLE fact_sales (
date_key int REFERENCES dim_date,
product_key int REFERENCES dim_product,
quantity int,
amount numeric(12, 2)
);
SELECT d.year, d.month, p.category, sum(f.amount) AS revenue
FROM fact_sales f
JOIN dim_date d USING (date_key)
JOIN dim_product p USING (product_key)
GROUP BY d.year, d.month, p.category;Why it works
- Queries have a predictable shape: join the fact to a few dimensions, group, aggregate.
- Dimensions are reused across many facts, so "category" means the same thing everywhere.
- Columnar warehouses are very good at scanning a narrow fact table and joining small dimensions.
Common mistakes
- Putting descriptive text in the fact table, which repeats it millions of times.
- Using natural keys from a source system that can change. A surrogate key such as
product_keyprotects you. - Forgetting to decide how a dimension changes over time, which is the subject of slowly changing dimensions.
Takeaway
Name the business process, choose the grain, list the measures, then list the dimensions that describe them. If you can say that in four sentences, the model is usually sound.
Comments