Database Facts and Dimensions
What you will learn
- What a fact table and a dimension table are
- What the grain of a fact table means and why to choose it first
- How to build and query a small warehouse
- What a surrogate key does in a warehouse
- How a slowly changing dimension keeps history
1. Two kinds of tables
Analytical designs (lesson 13.1) split data into two groups:
- A fact is something that happened and can be measured: a sale, a click, a payment. Each fact has numbers (quantity, amount) called measures. Facts go in a fact table, which is usually the biggest table, with a row for every event.
- A dimension describes the context of facts: when (date), what (product), where (store), who (customer). Dimensions go in dimension tables, which are smaller and full of descriptive text.
The fact table points to each dimension with a foreign key (lesson 3.1). Questions then read like sentences: "total amount (measure) by category (product dimension) and month (date dimension)".
2. Choose the grain first
The grain says exactly what one row of the fact table means. For our example:
One row = one product sold in one store on one day (the totals for that day).
Writing the grain down first prevents the most common design error: mixing rows of different meaning, such as some rows per sale and some rows per month. Every measure must make sense at that grain. Quantity and amount do. "Number of customers in the store" would not, because it belongs to the store and day, not to one product.
3. Building the warehouse
This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). It adds the tables of a small warehouse to your browser's copy; run the examples from top to bottom, and Reset data starts again.
This is a small sales warehouse for a made-up shop: six products, three stores and six months of days. The numbers come from a simple repeating rule, not from real sales. The dates are made by a recursive query (lesson 3.9), and the facts by a rule that combines the day number, the product and the store.
CREATE TABLE dim_date (date_key INTEGER PRIMARY KEY, full_date TEXT, month INTEGER, month_name TEXT, quarter INTEGER, year INTEGER);
CREATE TABLE dim_product (product_key INTEGER PRIMARY KEY, name TEXT, category TEXT, brand TEXT);
CREATE TABLE dim_store (store_key INTEGER PRIMARY KEY, name TEXT, city TEXT, region TEXT);
CREATE TABLE fact_sales (date_key INTEGER, product_key INTEGER, store_key INTEGER, quantity INTEGER, amount INTEGER);
INSERT INTO dim_product VALUES
(1, 'Tea 250g', 'Grocery', 'Hill'), (2, 'Rice 5kg', 'Grocery', 'Delta'),
(3, 'Notebook', 'Stationery', 'Page'), (4, 'Pen box', 'Stationery', 'Page'),
(5, 'Lamp', 'Home', 'Glow'), (6, 'Kettle', 'Home', 'Glow');
INSERT INTO dim_store VALUES
(1, 'Gulshan', 'Dhaka', 'Central'), (2, 'Mirpur', 'Dhaka', 'Central'), (3, 'Agrabad', 'Chattogram', 'South-East');
INSERT INTO dim_date
WITH RECURSIVE days(d) AS (SELECT date('2026-01-01') UNION ALL SELECT date(d, '+1 day') FROM days WHERE d < '2026-06-30')
SELECT CAST(strftime('%Y%m%d', d) AS INTEGER), d, CAST(strftime('%m', d) AS INTEGER),
substr('JanFebMarAprMayJun', (CAST(strftime('%m', d) AS INTEGER) - 1) * 3 + 1, 3),
(CAST(strftime('%m', d) AS INTEGER) - 1) / 3 + 1, CAST(strftime('%Y', d) AS INTEGER)
FROM days;
INSERT INTO fact_sales
WITH RECURSIVE days(i, d) AS (SELECT 0, date('2026-01-01') UNION ALL SELECT i + 1, date(d, '+1 day') FROM days WHERE d < '2026-06-30')
SELECT CAST(strftime('%Y%m%d', d) AS INTEGER), p.product_key, s.store_key,
(i + p.product_key * s.store_key) % 5 + 1,
((i + p.product_key * s.store_key) % 5 + 1) *
CASE p.product_key WHEN 1 THEN 120 WHEN 2 THEN 450 WHEN 3 THEN 60 WHEN 4 THEN 90 WHEN 5 THEN 700 ELSE 1200 END
FROM days CROSS JOIN dim_product p CROSS JOIN dim_store s
WHERE (i + p.product_key + s.store_key) % 4 = 0;
SELECT 'dim_date' AS table_name, COUNT(*) AS row_count FROM dim_date
UNION ALL SELECT 'dim_product', COUNT(*) FROM dim_product
UNION ALL SELECT 'dim_store', COUNT(*) FROM dim_store
UNION ALL SELECT 'fact_sales', COUNT(*) FROM fact_sales;
table_name row_count
----------- ---------
dim_date 181
dim_product 6
dim_store 3
fact_sales 815
(4 rows)
CREATE TABLE dim_date (date_key INTEGER PRIMARY KEY, full_date TEXT, month INTEGER, month_name TEXT, quarter INTEGER, year INTEGER);
CREATE TABLE dim_product (product_key INTEGER PRIMARY KEY, name TEXT, category TEXT, brand TEXT);
CREATE TABLE dim_store (store_key INTEGER PRIMARY KEY, name TEXT, city TEXT, region TEXT);
CREATE TABLE fact_sales (date_key INTEGER, product_key INTEGER, store_key INTEGER, quantity INTEGER, amount INTEGER);
INSERT INTO dim_product VALUES
(1, 'Tea 250g', 'Grocery', 'Hill'), (2, 'Rice 5kg', 'Grocery', 'Delta'),
(3, 'Notebook', 'Stationery', 'Page'), (4, 'Pen box', 'Stationery', 'Page'),
(5, 'Lamp', 'Home', 'Glow'), (6, 'Kettle', 'Home', 'Glow');
INSERT INTO dim_store VALUES
(1, 'Gulshan', 'Dhaka', 'Central'), (2, 'Mirpur', 'Dhaka', 'Central'), (3, 'Agrabad', 'Chattogram', 'South-East');
INSERT INTO dim_date
WITH RECURSIVE days(d) AS (SELECT date('2026-01-01') UNION ALL SELECT date(d, '+1 day') FROM days WHERE d < '2026-06-30')
SELECT CAST(strftime('%Y%m%d', d) AS INTEGER), d, CAST(strftime('%m', d) AS INTEGER),
substr('JanFebMarAprMayJun', (CAST(strftime('%m', d) AS INTEGER) - 1) * 3 + 1, 3),
(CAST(strftime('%m', d) AS INTEGER) - 1) / 3 + 1, CAST(strftime('%Y', d) AS INTEGER)
FROM days;
INSERT INTO fact_sales
WITH RECURSIVE days(i, d) AS (SELECT 0, date('2026-01-01') UNION ALL SELECT i + 1, date(d, '+1 day') FROM days WHERE d < '2026-06-30')
SELECT CAST(strftime('%Y%m%d', d) AS INTEGER), p.product_key, s.store_key,
(i + p.product_key * s.store_key) % 5 + 1,
((i + p.product_key * s.store_key) % 5 + 1) *
CASE p.product_key WHEN 1 THEN 120 WHEN 2 THEN 450 WHEN 3 THEN 60 WHEN 4 THEN 90 WHEN 5 THEN 700 ELSE 1200 END
FROM days CROSS JOIN dim_product p CROSS JOIN dim_store s
WHERE (i + p.product_key + s.store_key) % 4 = 0;
SELECT 'dim_date' AS table_name, COUNT(*) AS row_count FROM dim_date
UNION ALL SELECT 'dim_product', COUNT(*) FROM dim_product
UNION ALL SELECT 'dim_store', COUNT(*) FROM dim_store
UNION ALL SELECT 'fact_sales', COUNT(*) FROM fact_sales;
table_name row_count
----------- ---------
dim_date 181
dim_product 6
dim_store 3
fact_sales 815
(4 rows)
CREATE TABLE dim_date (date_key INTEGER PRIMARY KEY, full_date TEXT, month INTEGER, month_name TEXT, quarter INTEGER, year INTEGER);
CREATE TABLE dim_product (product_key INTEGER PRIMARY KEY, name TEXT, category TEXT, brand TEXT);
CREATE TABLE dim_store (store_key INTEGER PRIMARY KEY, name TEXT, city TEXT, region TEXT);
CREATE TABLE fact_sales (date_key INTEGER, product_key INTEGER, store_key INTEGER, quantity INTEGER, amount INTEGER);
INSERT INTO dim_product VALUES
(1, 'Tea 250g', 'Grocery', 'Hill'), (2, 'Rice 5kg', 'Grocery', 'Delta'),
(3, 'Notebook', 'Stationery', 'Page'), (4, 'Pen box', 'Stationery', 'Page'),
(5, 'Lamp', 'Home', 'Glow'), (6, 'Kettle', 'Home', 'Glow');
INSERT INTO dim_store VALUES
(1, 'Gulshan', 'Dhaka', 'Central'), (2, 'Mirpur', 'Dhaka', 'Central'), (3, 'Agrabad', 'Chattogram', 'South-East');
INSERT INTO dim_date
WITH RECURSIVE days(d) AS (SELECT date('2026-01-01') UNION ALL SELECT date(d, '+1 day') FROM days WHERE d < '2026-06-30')
SELECT CAST(strftime('%Y%m%d', d) AS INTEGER), d, CAST(strftime('%m', d) AS INTEGER),
substr('JanFebMarAprMayJun', (CAST(strftime('%m', d) AS INTEGER) - 1) * 3 + 1, 3),
(CAST(strftime('%m', d) AS INTEGER) - 1) / 3 + 1, CAST(strftime('%Y', d) AS INTEGER)
FROM days;
INSERT INTO fact_sales
WITH RECURSIVE days(i, d) AS (SELECT 0, date('2026-01-01') UNION ALL SELECT i + 1, date(d, '+1 day') FROM days WHERE d < '2026-06-30')
SELECT CAST(strftime('%Y%m%d', d) AS INTEGER), p.product_key, s.store_key,
(i + p.product_key * s.store_key) % 5 + 1,
((i + p.product_key * s.store_key) % 5 + 1) *
CASE p.product_key WHEN 1 THEN 120 WHEN 2 THEN 450 WHEN 3 THEN 60 WHEN 4 THEN 90 WHEN 5 THEN 700 ELSE 1200 END
FROM days CROSS JOIN dim_product p CROSS JOIN dim_store s
WHERE (i + p.product_key + s.store_key) % 4 = 0;
SELECT 'dim_date' AS table_name, COUNT(*) AS row_count FROM dim_date
UNION ALL SELECT 'dim_product', COUNT(*) FROM dim_product
UNION ALL SELECT 'dim_store', COUNT(*) FROM dim_store
UNION ALL SELECT 'fact_sales', COUNT(*) FROM fact_sales;
table_name row_count
----------- ---------
dim_date 181
dim_product 6
dim_store 3
fact_sales 815
(4 rows)
Notice the shape: three small dimension tables and one big fact table. Keys like 20260101 for the date are surrogate keys (lesson 2.5): numbers the warehouse invents, not values from the source systems. They stay stable even if the source system renumbers or reuses its own identifiers.
Look at a few joined rows, then ask for totals:
SELECT d.full_date, p.name AS product, s.name AS store, f.quantity, f.amount
FROM fact_sales f
JOIN dim_date d ON d.date_key = f.date_key
JOIN dim_product p ON p.product_key = f.product_key
JOIN dim_store s ON s.store_key = f.store_key
ORDER BY d.full_date, p.name LIMIT 3;
full_date product store quantity amount
---------- -------- ------- -------- ------
2026-01-01 Kettle Mirpur 3 3600
2026-01-01 Lamp Agrabad 1 700
2026-01-01 Notebook Gulshan 4 240
(3 rows)
SELECT SUM(amount) AS total_amount, SUM(quantity) AS total_quantity, COUNT(*) AS fact_rows FROM fact_sales;
total_amount total_quantity fact_rows
------------ -------------- ---------
1068370 2447 815
(1 row)
SELECT p.category, SUM(f.amount) AS amount
FROM fact_sales f JOIN dim_product p ON p.product_key = f.product_key
GROUP BY p.category ORDER BY amount DESC;
category amount
---------- ------
Home 773800
Grocery 233580
Stationery 60990
(3 rows)
SELECT d.full_date, p.name AS product, s.name AS store, f.quantity, f.amount
FROM fact_sales f
JOIN dim_date d ON d.date_key = f.date_key
JOIN dim_product p ON p.product_key = f.product_key
JOIN dim_store s ON s.store_key = f.store_key
ORDER BY d.full_date, p.name LIMIT 3;
full_date product store quantity amount
---------- -------- ------- -------- ------
2026-01-01 Kettle Mirpur 3 3600
2026-01-01 Lamp Agrabad 1 700
2026-01-01 Notebook Gulshan 4 240
(3 rows)
SELECT SUM(amount) AS total_amount, SUM(quantity) AS total_quantity, COUNT(*) AS fact_rows FROM fact_sales;
total_amount total_quantity fact_rows
------------ -------------- ---------
1068370 2447 815
(1 row)
SELECT p.category, SUM(f.amount) AS amount
FROM fact_sales f JOIN dim_product p ON p.product_key = f.product_key
GROUP BY p.category ORDER BY amount DESC;
category amount
---------- ------
Home 773800
Grocery 233580
Stationery 60990
(3 rows)
SELECT d.full_date, p.name AS product, s.name AS store, f.quantity, f.amount
FROM fact_sales f
JOIN dim_date d ON d.date_key = f.date_key
JOIN dim_product p ON p.product_key = f.product_key
JOIN dim_store s ON s.store_key = f.store_key
ORDER BY d.full_date, p.name LIMIT 3;
full_date product store quantity amount
---------- -------- ------- -------- ------
2026-01-01 Kettle Mirpur 3 3600
2026-01-01 Lamp Agrabad 1 700
2026-01-01 Notebook Gulshan 4 240
(3 rows)
SELECT SUM(amount) AS total_amount, SUM(quantity) AS total_quantity, COUNT(*) AS fact_rows FROM fact_sales;
total_amount total_quantity fact_rows
------------ -------------- ---------
1068370 2447 815
(1 row)
SELECT p.category, SUM(f.amount) AS amount
FROM fact_sales f JOIN dim_product p ON p.product_key = f.product_key
GROUP BY p.category ORDER BY amount DESC;
category amount
---------- ------
Home 773800
Grocery 233580
Stationery 60990
(3 rows)
Every query follows the same pattern: join the fact table to the dimensions you need, filter on dimension attributes, group by dimension attributes, and add up the measures. Lesson 13.3 shows more of these.
A warehouse can also be built from the real tables of the sample database. A fact table is just a join of the event table to its context:
Every order line becomes a fact, with the date, the product and the customer's country as context:
CREATE TABLE fact_lines AS
SELECT o.order_date AS full_date, oi.product_id AS product_key, c.country AS country,
oi.quantity AS quantity, ROUND(oi.quantity * oi.unit_price, 2) AS amount
FROM order_items oi
JOIN orders o ON o.order_id = oi.order_id
JOIN customers c ON c.customer_id = o.customer_id;
SELECT COUNT(*) AS fact_rows FROM fact_lines;
SELECT country, ROUND(SUM(amount), 2) AS amount FROM fact_lines GROUP BY country ORDER BY amount DESC, country LIMIT 3;
fact_rows
---------
5790
(1 row)
country amount
-------------- --------
United Kingdom 27526.63
Brazil 19655.22
Kenya 19451.41
(3 rows)
Every ledger row becomes a fact, with the date, the account type and the branch as context:
CREATE TABLE fact_ledger AS
SELECT t.txn_date AS full_date, a.account_type AS account_type, b.name AS branch,
t.kind AS kind, t.amount_cents AS amount_cents
FROM transactions t
JOIN accounts a ON a.account_id = t.account_id
JOIN branches b ON b.branch_id = a.branch_id;
SELECT COUNT(*) AS fact_rows FROM fact_ledger;
SELECT branch, SUM(amount_cents) AS cents FROM fact_ledger WHERE kind = 'deposit' GROUP BY branch ORDER BY cents DESC, branch LIMIT 3;
fact_rows
---------
7415
(1 row)
branch cents
---------- --------
Central 19288700
University 18033200
Airport 16668100
(3 rows)
Every submission becomes a fact, with the date, the course and the department as context:
CREATE TABLE fact_submissions AS
SELECT sub.submitted_on AS full_date, co.title AS course, d.name AS department, sub.points AS points
FROM submissions sub
JOIN assignments a ON a.assignment_id = sub.assignment_id
JOIN sections se ON se.section_id = a.section_id
JOIN courses co ON co.course_id = se.course_id
JOIN departments d ON d.department_id = co.department_id
WHERE sub.points IS NOT NULL;
SELECT COUNT(*) AS fact_rows FROM fact_submissions;
SELECT department, ROUND(AVG(points), 1) AS average_points FROM fact_submissions GROUP BY department ORDER BY average_points DESC, department LIMIT 3;
fact_rows
---------
3879
(1 row)
department average_points
---------- --------------
Science 37.5
Computing 35.7
Arts 34.0
(3 rows)
4. Dimensions change: keeping history
A product's category rarely changes, but a customer moves, a store changes region, a salesperson changes team. If a customer's city is simply overwritten, old facts suddenly appear to belong to the new city and past reports change.
The usual cure is a slowly changing dimension, type 2 (often written SCD2): never overwrite, add a new row and mark which one is current.
CREATE TABLE dim_customer (customer_key INTEGER PRIMARY KEY, customer_id TEXT, city TEXT, valid_from TEXT, valid_to TEXT, is_current INTEGER);
INSERT INTO dim_customer VALUES (1, 'C-100', 'Dhaka', '2026-01-01', NULL, 1);
(1 row changed)
C-100 moves on 2026-04-01: close the old row, add a new one:
UPDATE dim_customer SET valid_to = '2026-03-31', is_current = 0 WHERE customer_id = 'C-100' AND is_current = 1;
INSERT INTO dim_customer VALUES (2, 'C-100', 'Chattogram', '2026-04-01', NULL, 1);
SELECT * FROM dim_customer ORDER BY customer_key;
customer_key customer_id city valid_from valid_to is_current
------------ ----------- ---------- ---------- ---------- ----------
1 C-100 Dhaka 2026-01-01 2026-03-31 0
2 C-100 Chattogram 2026-04-01 NULL 1
(2 rows)
Where did the customer live on 15 February?
SELECT city FROM dim_customer
WHERE customer_id = 'C-100' AND '2026-02-15' >= valid_from AND (valid_to IS NULL OR '2026-02-15' <= valid_to);
city
-----
Dhaka
(1 row)
CREATE TABLE dim_customer (customer_key INTEGER PRIMARY KEY, customer_id TEXT, city TEXT, valid_from TEXT, valid_to TEXT, is_current INTEGER);
INSERT INTO dim_customer VALUES (1, 'C-100', 'Dhaka', '2026-01-01', NULL, 1);
(1 row changed)
C-100 moves on 2026-04-01: close the old row, add a new one:
UPDATE dim_customer SET valid_to = '2026-03-31', is_current = 0 WHERE customer_id = 'C-100' AND is_current = 1;
INSERT INTO dim_customer VALUES (2, 'C-100', 'Chattogram', '2026-04-01', NULL, 1);
SELECT * FROM dim_customer ORDER BY customer_key;
customer_key customer_id city valid_from valid_to is_current
------------ ----------- ---------- ---------- ---------- ----------
1 C-100 Dhaka 2026-01-01 2026-03-31 0
2 C-100 Chattogram 2026-04-01 NULL 1
(2 rows)
Where did the customer live on 15 February?
SELECT city FROM dim_customer
WHERE customer_id = 'C-100' AND '2026-02-15' >= valid_from AND (valid_to IS NULL OR '2026-02-15' <= valid_to);
city
-----
Dhaka
(1 row)
CREATE TABLE dim_customer (customer_key INTEGER PRIMARY KEY, customer_id TEXT, city TEXT, valid_from TEXT, valid_to TEXT, is_current INTEGER);
INSERT INTO dim_customer VALUES (1, 'C-100', 'Dhaka', '2026-01-01', NULL, 1);
(1 row changed)
C-100 moves on 2026-04-01: close the old row, add a new one:
UPDATE dim_customer SET valid_to = '2026-03-31', is_current = 0 WHERE customer_id = 'C-100' AND is_current = 1;
INSERT INTO dim_customer VALUES (2, 'C-100', 'Chattogram', '2026-04-01', NULL, 1);
SELECT * FROM dim_customer ORDER BY customer_key;
customer_key customer_id city valid_from valid_to is_current
------------ ----------- ---------- ---------- ---------- ----------
1 C-100 Dhaka 2026-01-01 2026-03-31 0
2 C-100 Chattogram 2026-04-01 NULL 1
(2 rows)
Where did the customer live on 15 February?
SELECT city FROM dim_customer
WHERE customer_id = 'C-100' AND '2026-02-15' >= valid_from AND (valid_to IS NULL OR '2026-02-15' <= valid_to);
city
-----
Dhaka
(1 row)
The last query asked where the customer lived on 15 February: Dhaka. Facts recorded before April point to customer row 1 and show Dhaka; facts after April point to row 2 and show Chattogram. This is why the warehouse uses its own customer_key and not the business customer_id: one customer, two rows, two keys.
(Other choices exist: type 1 simply overwrites and loses history; type 3 keeps just one previous value in an extra column. Type 2 is the most common when history matters.)
Worked example: design the warehouse for a bus company
A made-up bus company wants to analyse tickets sold.
Step 1, grain: one row = one ticket sold.
Step 2, dimensions: date (when), route (from, to, distance), bus (type, seats), passenger type (adult, student, senior), sales channel (counter, app).
Step 3, measures: price paid, discount given. ("Seats on the bus" is not a measure of a ticket; it describes the bus, so it belongs in the bus dimension.)
Step 4, history: a route can be renamed and a bus can change type, so route and bus use type 2 rows.
Sketch:
dim_date dim_route dim_bus
\ | /
fact_tickets (price, discount)
/ |
dim_passenger_type dim_channel
Common mistakes
- Not deciding the grain. Rows of mixed meaning give wrong totals.
- Putting descriptive text in the fact table. Names and categories belong in dimensions; repeating them in every fact row wastes space and invites inconsistency.
- Adding measures that do not fit the grain, such as a store's monthly rent in a per-sale row (it would be counted once per sale).
- Overwriting dimension rows when history matters, so old reports change.
- Using source-system IDs as the only keys, which breaks when two systems reuse the same ID.
Key takeaways
- Facts are measurable events (big tables of numbers); dimensions describe their context (smaller tables of text).
- Decide the grain, the meaning of one fact row, before anything else.
- Queries join the fact table to dimensions, filter and group on dimension columns, and sum the measures.
- Use surrogate keys in the warehouse.
- A type 2 slowly changing dimension keeps history by adding rows with valid-from and valid-to dates.
Practice
1. In "total sales amount by store and month", which words are measures and which are dimensions?
Show answer
Measure: sales amount. Dimensions: store and month (date).
2. What is the grain of fact_sales in the lesson?
Show answer
One row = one product sold in one store on one day.
3. Why would "number of staff in the store" be a poor measure in fact_sales?
Show answer
It does not belong to a single product sale. Adding it up over sale rows would count it many times. It describes the store and should live in the store dimension, or in a separate fact table with a store-and-day grain.
4. What is wrong with overwriting a customer's city when they move?
Show answer
Old sales would immediately appear to belong to the new city, so past reports change. A type 2 dimension keeps the old row.
5. After the move in the lesson, how many rows does dim_customer have for C-100, and which one has is_current = 1?
Show answer
Two rows; the one with customer_key 2 (Chattogram) is current.
6. Sketch the facts and dimensions for a library that wants to analyse book loans.
Show answer
For example, grain: one row = one loan. Dimensions: date borrowed, book (title, author, category), member (age group, branch), branch. Measures: days kept, late fee.