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 3 of 6 · Concept · 20 min · revision 2

Dimensions, Surrogate Keys and Conformance

How to design dimension tables: flattened hierarchies, surrogate keys and an "Unknown" member, one date dimension playing several roles, conformed dimensions that let two fact tables be compared without double counting, and the bus matrix that plans them.

Contentsand lesson path

What you will learn

  • 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. Why it matters

Fact tables hold the numbers, but people meet a warehouse through its dimensions: every filter, every row label and every drill-down in a dashboard is a dimension attribute. Good dimensions make questions easy to ask; careless ones make the same question give two answers in two reports. This lesson covers the design choices that matter most: what goes into a dimension row, which key the facts use, how one date table serves several dates, and how separate fact tables share dimensions so they can be compared. Run the examples in a new database in the sql-lab container.

Terminal
docker exec sql-lab psql -U postgres -X -q -c "SET client_min_messages = warning" \
  -c "DROP DATABASE IF EXISTS dims" -c "CREATE DATABASE dims"

Then open it with docker exec -it sql-lab psql -U postgres -d dims and paste the examples in order.

02. Dimension rows: wide, descriptive, flattened

A dimension row describes one member, such as one product, in words people use: name, brand, colour, size, and the levels above it. A hierarchy like product → subcategory → category → department is stored as columns on the same row, repeated for every product. That redundancy is deliberate. Analysts drill from department to product by grouping on different columns of one table, with one join to the fact. Store readable values ("Paperback", not "PB") and replace NULLs with explicit labels such as "Not applicable", so reports do not show blank row headers.

Each dimension also has two kinds of key. The natural key (or business key) comes from the source system, for example the CRM's customer number. The surrogate key is a meaningless integer generated by the warehouse, and it is what fact tables store. Surrogate keys let one customer have several rows when you track history (lesson 5). They protect the warehouse when a source reuses or reformats its IDs, and they let customers from two source systems sit in one table. They also make a special Unknown member possible: a row, often with key -1, that facts point to when the source did not say which member they belong to.

SQL · psql, database dims
CREATE TABLE dim_customer (
  customer_key  int GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
  source_system text NOT NULL,
  source_id     text NOT NULL,          -- the natural key
  name          text NOT NULL,
  segment       text NOT NULL,
  UNIQUE (source_system, source_id)
);
INSERT INTO dim_customer VALUES (-1, 'none', 'unknown', 'Unknown', 'Unknown');
INSERT INTO dim_customer (source_system, source_id, name, segment) VALUES
  ('crm', 'C-001', 'Ana', 'Retail'), ('crm', 'C-002', 'Ben', 'Trade'),
  ('shop', '77', 'Cai', 'Retail');  -- a second source with its own ids

CREATE TABLE fact_sales (customer_key int NOT NULL REFERENCES dim_customer,
                         amount numeric(8,2));
-- the till could not identify the customer for the last sale
INSERT INTO fact_sales VALUES (1, 40), (2, 25), (3, 60), (-1, 15);

SELECT c.segment, count(*) AS sales, sum(f.amount) AS revenue
FROM fact_sales f JOIN dim_customer c USING (customer_key)
GROUP BY c.segment ORDER BY c.segment;
Expected output
 segment | sales | revenue 
---------+-------+---------
 Retail  |     2 |  100.00
 Trade   |     1 |   25.00
 Unknown |     1 |   15.00
(3 rows)

All 140 of revenue appear, including the anonymous sale under "Unknown". Had that fact stored a NULL key, an inner join would have dropped it and the report would silently show 125. GENERATED BY DEFAULT lets you insert the -1 row by hand while ordinary rows get generated keys. Note that the natural key is unique per source system, not on its own: two systems can both have a customer "77".

03. One date dimension, many roles

Almost every fact has a date, so almost every warehouse has a date dimension: one row per calendar day, generated in advance, with the attributes people filter on: month, quarter, weekday, holiday flags, fiscal periods. Its key is often an integer such as 20260307, which is readable and sorts in date order.

Facts often carry several dates: an order has an order date and a ship date. You do not build two date tables. The same table plays two roles, joined twice under different names, often through views named after the role so that report columns are clear.

SQL · psql, database dims
CREATE TABLE dim_date AS
SELECT to_char(d, 'YYYYMMDD')::int AS date_key, d::date AS full_date,
       to_char(d, 'Dy') AS weekday, extract(isodow FROM d) >= 6 AS is_weekend
FROM generate_series(date '2026-03-01', date '2026-03-31', interval '1 day') AS d;
CREATE VIEW dim_order_date AS
  SELECT date_key AS order_date_key, weekday AS order_weekday FROM dim_date;
CREATE VIEW dim_ship_date AS
  SELECT date_key AS ship_date_key, weekday AS ship_weekday FROM dim_date;

CREATE TABLE fact_shipments (order_id int, order_date_key int, ship_date_key int);
INSERT INTO fact_shipments VALUES
  (1, 20260306, 20260309), (2, 20260307, 20260309), (3, 20260309, 20260310);

SELECT o.order_weekday, s.ship_weekday, count(*) AS orders
FROM fact_shipments f
JOIN dim_order_date o USING (order_date_key)
JOIN dim_ship_date  s USING (ship_date_key)
GROUP BY 1, 2 ORDER BY 1, 2;
Expected output
 order_weekday | ship_weekday | orders 
---------------+--------------+--------
 Fri           | Mon          |      1
 Mon           | Tue          |      1
 Sat           | Mon          |      1
(3 rows)

The report shows, for example, that the Friday and Saturday orders both shipped on Monday, a question about two dates answered from one table. A role-playing dimension is any dimension used in several roles; customers can play "buyer" and "recipient" the same way.

04. Conformed dimensions and drill-across

A business has many processes: sales, returns, shipments, web visits. Each gets its own fact table at its own grain. Questions that cross processes, such as "return rate by category", need the facts to share dimensions. A conformed dimension is one dimension, or exact copies with the same keys and attribute values, used by several fact tables. If sales and returns both use the same dim_product, then "Books" means the same products on both sides.

Comparing two fact tables has a trap. Joining them directly on the shared key multiplies rows: every sales row of a product pairs with every return row of that product, a fan-out. The safe pattern, called drill-across, aggregates each fact separately to the same dimension attributes, then joins the small results.

SQL · psql, database dims
CREATE TABLE dim_product (product_key int PRIMARY KEY, product text, category text);
INSERT INTO dim_product VALUES (1, 'Atlas', 'Books'), (2, 'Novel', 'Books'),
                               (3, 'Chess set', 'Games');
CREATE TABLE fact_sale_lines (product_key int, qty int);
CREATE TABLE fact_return_lines (product_key int, qty int);
INSERT INTO fact_sale_lines VALUES (1, 2), (1, 3), (2, 5), (3, 4);
INSERT INTO fact_return_lines VALUES (1, 1), (1, 1), (3, 1);

-- wrong: joining two facts directly multiplies rows
SELECT p.category, sum(s.qty) AS sold, sum(r.qty) AS returned
FROM fact_sale_lines s
JOIN dim_product p USING (product_key)
LEFT JOIN fact_return_lines r USING (product_key)
GROUP BY p.category ORDER BY p.category;

-- drill-across: aggregate each fact, then join on the conformed attribute
WITH sold AS (
  SELECT p.category, sum(s.qty) AS sold
  FROM fact_sale_lines s JOIN dim_product p USING (product_key) GROUP BY 1
), returned AS (
  SELECT p.category, sum(r.qty) AS returned
  FROM fact_return_lines r JOIN dim_product p USING (product_key) GROUP BY 1
)
SELECT category, sold, coalesce(returned, 0) AS returned,
       round(100.0 * coalesce(returned, 0) / sold, 1) AS return_pct
FROM sold LEFT JOIN returned USING (category) ORDER BY category;
Expected output
 category | sold | returned 
----------+------+----------
 Books    |   15 |        4
 Games    |    4 |        1
(2 rows)

 category | sold | returned | return_pct 
----------+------+----------+------------
 Books    |   10 |        2 |       20.0
 Games    |    4 |        1 |       25.0
(2 rows)

The direct join reports 15 books sold and 4 returned; the truth is 10 and 2. The two Atlas sales rows each paired with the two Atlas return rows, so each side was counted twice. Drill-across gives 10 sold, 2 returned and a 20 % return rate. It only works because both facts use the same product dimension: if the returns team had their own product table with different category values, the final join would line up rows that do not mean the same thing.

05. Plan the shared dimensions with a bus matrix

Conformed dimensions are easiest to agree on before anyone builds tables. The enterprise bus matrix is the planning tool for that. Each row is a business process, which will become one or more fact tables. Each column is a dimension. A mark in a cell says "this process uses this dimension". Reading down a column shows every process that must share that dimension, and therefore every team that must agree on its keys and attribute values.

Bus matrix for a small retailer
Business process   Date  Product  Customer  Store  Promotion
Retail sales        X       X        X        X        X
Returns             X       X        X        X
Inventory           X       X                 X
Purchase orders     X       X

The Product column has a mark in every row, so the product dimension must be conformed across all four processes before inventory can be compared with sales. The matrix is also a roadmap: teams build one row at a time, and each new process reuses the dimensions that already exist instead of creating private copies. Private copies are how "stovepipe" marts appear, each internally consistent and impossible to compare.

06. Check your understanding

Practice check · 3 questions

Keys, roles and conformance

Each question describes a new situation. Pick the best answer.

Q1. An analyst joins `fact_orders` (5 rows for product 7) and `fact_refunds` (2 rows for product 7) on `product_key`, then sums both quantities. Why are both totals too high for product 7?
Q2. Some web orders arrive without a campaign. Why do many designs point them to a campaign dimension row with key -1, labelled "Unknown", instead of storing a NULL key?
Q3. A loan fact has an application date, an approval date and a payout date. How should the dates be modelled?
Practice only: not graded, not saved, not evidence.

07. Apply it

For the subscription business in the practice project:

  1. Draw the bus matrix: rows for sign-ups, payments and plan changes; columns for date, customer, plan and any others you need.
  2. Design the plan dimension: natural key, surrogate key, the attributes analysts filter on, and an Unknown member.
  3. List every date each fact carries and the role name you will give it.
  4. Write a drill-across query outline for "payments per sign-up by plan", aggregating each fact separately.

08. Review prompt

Without looking back, explain:

  • why hierarchies are flattened into dimension columns in a star schema;
  • the difference between a natural key and a surrogate key, and three reasons facts store the surrogate key;
  • what an Unknown member is for;
  • what a role-playing dimension is;
  • why joining two fact tables directly gives inflated totals, and what drill-across does instead;
  • what the rows, columns and marks of a bus matrix mean.

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