Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Worked example · 30 min · revision 2

Worked Example: A Star Schema for Online Retail

Design and build a sales star schema for an online shop in PostgreSQL 17, from the business questions to the grain, dimensions, measures and load, reconcile it with the source, then add returns as a second process with conformed dimensions and a bus matrix.

Contentsand lesson path

What you will learn

  • Declare the grain of a business process and design transaction, periodic-snapshot or accumulating-snapshot fact tables with correctly classified additive, semi-additive and non-additive measures.
  • Design dimension tables with surrogate keys and hierarchies, and choose between star, snowflake and one-big-table layouts for a use case.
  • Build a bus matrix that maps business processes to conformed dimensions shared across subject areas.

Prerequisites: Relational Data Modeling

01. The problem

An online shop sells books and games. Its finance and merchandising teams want answers that today take a day of spreadsheet work:

  • net revenue by product category and month, after line discounts;
  • the same split by customer country, including orders from guests who did not log in;
  • the return rate by category, by value.

You have read-only copies of the shop's operational tables. You will design a star schema in the order Kimball recommends (business process, grain, dimensions, facts), build it with SQL, check it against the source, and then extend it with a second process. Use the sql-lab container (PostgreSQL 17) from earlier lessons. Save the source extract below as source.sql and load it.

SQL · source.sql
CREATE TABLE src_customers (customer_id text PRIMARY KEY, name text,
                            city text, country text);
CREATE TABLE src_products (sku text PRIMARY KEY, name text, subcategory text,
                           category text, department text);
CREATE TABLE src_orders (order_number text PRIMARY KEY,
                         customer_id text,   -- NULL for guest checkout
                         ordered_at timestamp NOT NULL);
CREATE TABLE src_order_lines (order_number text, line_no int, sku text,
                              qty int, unit_price numeric(8,2),
                              line_discount numeric(8,2),
                              PRIMARY KEY (order_number, line_no));
CREATE TABLE src_returns (return_id text PRIMARY KEY, order_number text,
                          line_no int, returned_at timestamp, qty int);

INSERT INTO src_customers VALUES
  ('C1', 'Ana', 'Leeds', 'UK'), ('C2', 'Ben', 'Lyon', 'FR');
INSERT INTO src_products VALUES
  ('B-ATL', 'Atlas',     'Maps',        'Books', 'Media'),
  ('B-NOV', 'Novel',     'Fiction',     'Books', 'Media'),
  ('G-CHS', 'Chess set', 'Board games', 'Games', 'Toys'),
  ('G-PUZ', 'Puzzle',    'Puzzles',     'Games', 'Toys');
INSERT INTO src_orders VALUES
  ('SO-1001', 'C1', '2026-01-14 10:02'), ('SO-1002', NULL, '2026-01-20 18:40'),
  ('SO-1003', 'C2', '2026-02-03 09:15'), ('SO-1004', 'C1', '2026-02-17 21:30');
INSERT INTO src_order_lines VALUES
  ('SO-1001', 1, 'B-ATL', 1, 30, 0), ('SO-1001', 2, 'G-CHS', 1, 45, 5),
  ('SO-1002', 1, 'B-NOV', 2, 12, 0),
  ('SO-1003', 1, 'G-CHS', 1, 45, 0), ('SO-1003', 2, 'G-PUZ', 3, 10, 3),
  ('SO-1004', 1, 'B-ATL', 2, 30, 6), ('SO-1004', 2, 'B-NOV', 1, 12, 0);
INSERT INTO src_returns VALUES
  ('R-1', 'SO-1001', 2, '2026-01-25 12:00', 1),
  ('R-2', 'SO-1003', 2, '2026-02-10 16:20', 1);
SELECT count(*) AS order_lines, sum(qty * unit_price - line_discount) AS net
FROM src_order_lines;
Terminal
docker exec sql-lab psql -U postgres -X -q -c "SET client_min_messages = warning" \
  -c "DROP DATABASE IF EXISTS retail" -c "CREATE DATABASE retail"
docker exec -i sql-lab psql -U postgres -d retail -X -q < source.sql
Expected output
 order_lines |  net   
-------------+--------
           7 | 232.00
(1 row)

Keep the source total in mind: 7 order lines and 232.00 of net sales. Your star schema must reproduce that number exactly.

02. Step 1: Choose the business process and declare the grain

A business process is something the organisation does that produces measurable events: taking orders, handling returns, receiving stock. Start with the process that answers the most important questions; here that is sales, because two of the three questions are about sales. Returns come later, as a separate process with its own fact table.

Next, declare the grain in one sentence: one row per order line. Why not one row per order? Category is a property of a product, and one order can contain a book and a game, so an order-level row cannot be split by category. Why not one row per product per day? That would throw away which customer bought what, and the country question needs the customer. The order line is the most atomic level the source captures, so every total the teams want can be rolled up from it.

03. Step 2: Choose the dimensions

Ask what describes one order line. Each answer becomes a dimension:

  • Date: the order date. A generated date dimension gives month and quarter (and, in a real warehouse, weekdays, holidays and fiscal periods) without date arithmetic in every query.
  • Product: the SKU with its whole hierarchy flattened onto one row: subcategory, category, department.
  • Customer: name, city and country, plus an Unknown member for guest orders, so that guest revenue is kept and labelled rather than dropped.

The order number also describes a line, but it has no attributes of its own: everything about the order is already in the other dimensions. It goes straight into the fact table as a degenerate dimension, a dimension key with no dimension table. It lets analysts count orders and trace a line back to the source. Every dimension gets a surrogate key, and keeps its natural key (sku, customer_id) as an attribute.

SQL · dimensions.sql
CREATE TABLE dim_date AS
SELECT to_char(d, 'YYYYMMDD')::int AS date_key, d::date AS full_date,
       to_char(d, 'YYYY-MM') AS month, 'Q' || extract(quarter FROM d) AS quarter
FROM generate_series(date '2026-01-01', date '2026-12-31', interval '1 day') AS d;
ALTER TABLE dim_date ADD PRIMARY KEY (date_key);

CREATE TABLE dim_product (
  product_key int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  sku text UNIQUE NOT NULL, product text, subcategory text,
  category text, department text
);
INSERT INTO dim_product (sku, product, subcategory, category, department)
SELECT sku, name, subcategory, category, department FROM src_products ORDER BY sku;

CREATE TABLE dim_customer (
  customer_key int GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
  customer_id text UNIQUE NOT NULL, customer text, city text, country text
);
INSERT INTO dim_customer VALUES (-1, 'guest', 'Guest', 'Unknown', 'Unknown');
INSERT INTO dim_customer (customer_id, customer, city, country)
SELECT customer_id, name, city, country FROM src_customers ORDER BY customer_id;

SELECT (SELECT count(*) FROM dim_date) AS dates,
       (SELECT count(*) FROM dim_product) AS products,
       (SELECT count(*) FROM dim_customer) AS customers;
Terminal
docker exec -i sql-lab psql -U postgres -d retail -X -q < dimensions.sql
Expected output
 dates | products | customers 
-------+----------+-----------
   365 |        4 |         3
(1 row)

04. Step 3: Choose the measures and load the fact table

Measures are the numbers recorded for one order line: qty, gross_amount (qty × unit price), discount_amount and net_amount. All four are additive, so any report can sum them along any dimension. The unit price is non-additive (adding prices means nothing), so it is not stored as a measure; a report that needs an average price divides sum(gross_amount) by sum(qty).

The load joins each source line to its order, then looks up the surrogate key of each dimension through the natural key. A guest order has no customer, so coalesce(c.customer_key, -1) sends it to the Unknown member. Use a LEFT JOIN for that lookup: an inner join would silently drop guest lines.

SQL · fact_sales.sql
CREATE TABLE fact_sales (
  date_key        int NOT NULL REFERENCES dim_date,
  product_key     int NOT NULL REFERENCES dim_product,
  customer_key    int NOT NULL REFERENCES dim_customer,
  order_number    text NOT NULL,             -- degenerate dimension
  line_no         int NOT NULL,
  qty             int NOT NULL,
  gross_amount    numeric(10,2) NOT NULL,
  discount_amount numeric(10,2) NOT NULL,
  net_amount      numeric(10,2) NOT NULL,
  PRIMARY KEY (order_number, line_no)
);
INSERT INTO fact_sales
SELECT to_char(o.ordered_at, 'YYYYMMDD')::int, p.product_key,
       coalesce(c.customer_key, -1), l.order_number, l.line_no, l.qty,
       l.qty * l.unit_price, l.line_discount,
       l.qty * l.unit_price - l.line_discount
FROM src_order_lines l
JOIN src_orders o       ON o.order_number = l.order_number
JOIN dim_product p      ON p.sku = l.sku
LEFT JOIN dim_customer c ON c.customer_id = o.customer_id;

SELECT 'fact' AS side, count(*) AS lines, sum(net_amount) AS net FROM fact_sales
UNION ALL
SELECT 'source', count(*), sum(qty * unit_price - line_discount)
FROM src_order_lines;
Terminal
docker exec -i sql-lab psql -U postgres -d retail -X -q < fact_sales.sql
Expected output
  side  | lines |  net   
--------+-------+--------
 fact   |     7 | 232.00
 source |     7 | 232.00
(2 rows)

The last query is a reconciliation test: the fact table must have the same row count and total as the source. Keep it and run it after every load. If the counts differ, a lookup lost or duplicated rows; if only the totals differ, a measure is computed differently.

05. Step 4: Answer the questions

Every question now follows the same pattern: join the fact to the dimensions you need, group by their attributes, and sum measures. The second query counts distinct orders with the degenerate dimension. Distinct counts need care. Each order has one order date, so monthly order counts add up. Distinct customers do not: a customer who bought in January and February would be counted twice if you added the two months, so count again at each level.

SQL · psql, database retail
SELECT d.month, p.category, sum(f.net_amount) AS net_revenue
FROM fact_sales f
JOIN dim_date d    USING (date_key)
JOIN dim_product p USING (product_key)
GROUP BY 1, 2 ORDER BY 1, 2;

SELECT c.country, count(DISTINCT f.order_number) AS orders,
       sum(f.net_amount) AS net_revenue
FROM fact_sales f JOIN dim_customer c USING (customer_key)
GROUP BY 1 ORDER BY 1;
Expected output
  month  | category | net_revenue 
---------+----------+-------------
 2026-01 | Books    |       54.00
 2026-01 | Games    |       40.00
 2026-02 | Books    |       66.00
 2026-02 | Games    |       72.00
(4 rows)

 country | orders | net_revenue 
---------+--------+-------------
 FR      |      1 |       72.00
 UK      |      2 |      136.00
 Unknown |      1 |       24.00
(3 rows)

Both queries add up to 232.00, the source total, and the guest order is visible under "Unknown" instead of missing.

06. Step 5: Add returns as a second process

Returns are a different business process: they happen on a different date, in different quantities, and a return is a new event, not a change to the sale. So they get their own fact table, at the grain one row per returned order line. They must use the same product, customer and date dimensions as sales, so the two can be compared by category or country. The refund is the line's net price per unit times the quantity returned. The date key here plays the role "return date", a second role for the same date dimension.

SQL · fact_returns.sql
CREATE TABLE fact_returns (
  return_date_key int NOT NULL REFERENCES dim_date,
  product_key     int NOT NULL REFERENCES dim_product,
  customer_key    int NOT NULL REFERENCES dim_customer,
  order_number    text NOT NULL,
  return_id       text PRIMARY KEY,
  qty             int NOT NULL,
  refund_amount   numeric(10,2) NOT NULL
);
INSERT INTO fact_returns
SELECT to_char(r.returned_at, 'YYYYMMDD')::int, s.product_key, s.customer_key,
       r.order_number, r.return_id, r.qty,
       round(s.net_amount / s.qty * r.qty, 2)
FROM src_returns r
JOIN fact_sales s ON s.order_number = r.order_number AND s.line_no = r.line_no;

WITH sold AS (
  SELECT p.category, sum(f.net_amount) AS net_sales
  FROM fact_sales f JOIN dim_product p USING (product_key) GROUP BY 1
), refunded AS (
  SELECT p.category, sum(r.refund_amount) AS refunds
  FROM fact_returns r JOIN dim_product p USING (product_key) GROUP BY 1
)
SELECT category, net_sales, coalesce(refunds, 0) AS refunds,
       round(100 * coalesce(refunds, 0) / net_sales, 1) AS return_pct
FROM sold LEFT JOIN refunded USING (category) ORDER BY category;
Terminal
docker exec -i sql-lab psql -U postgres -d retail -X -q < fact_returns.sql
Expected output
 category | net_sales | refunds | return_pct 
----------+-----------+---------+------------
 Books    |    120.00 |       0 |        0.0
 Games    |    112.00 |   49.00 |       43.8
(2 rows)

The comparison is a drill-across: each fact is aggregated to category on its own, then the two small results are joined. That is valid only because "Games" comes from the one shared dim_product. Games lost 49 of 112 to returns, 43.8 %: the chess set returned from SO-1001 (40 after its discount) and one of the three puzzles from SO-1003 (27 / 3 = 9).

07. Step 6: Record the design in a bus matrix

Finally, write down what you built, and what comes next, as a bus matrix: business processes as rows, dimensions as columns, a mark where a process uses a dimension. The roles of the date dimension are written in the cell. Inventory is planned but not built: when it comes, it will reuse date and product, so stock can be compared with sales.

Bus matrix for the shop
Process              Grain                     Date          Product  Customer
Sales (built)        one row per order line    order date       X        X
Returns (built)      one row per return line   return date      X        X
Inventory (planned)  one row per SKU per day   snapshot day     X

08. Check your understanding

Practice check · 3 questions

Design decisions in the retail star

These questions change one detail of the worked example. Pick the best answer.

Q1. A colleague wants a `dim_order` table whose only column besides its key is `order_number`. What is the better design, and why?
Q2. The fact load uses `JOIN dim_customer c ON c.customer_id = o.customer_id` instead of the LEFT JOIN with coalesce. What does the reconciliation query show?
Q3. A report shows 12 distinct UK customers in March and 9 in April. Can you report 21 distinct UK customers for the two months?
Practice only: not graded, not saved, not evidence.

09. Apply it

Repeat the worked example for the practice project, a subscription business:

  1. Pick the first process (payments), declare its grain and list its dimensions and additive measures.
  2. Build the plan and customer dimensions with surrogate keys and an Unknown member, then load a payments fact from a small source extract you write yourself.
  3. Write the reconciliation test before any report query.
  4. Add sign-ups as a second process that reuses the same dimensions, and update your bus matrix.

10. Review prompt

Without looking back, list the four design steps in order and give the decision you made at each step for the shop. Then explain why the order line was chosen as the grain, what a degenerate dimension is, why the customer lookup uses a LEFT JOIN, why returns have their own fact table, and what the reconciliation test protects against.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check