SQL course · Module 8: Database design · Lesson 30 of 40
Quick answer: Normalization vs denormalization is a choice about where each fact is stored. A normalized design stores each fact once, which keeps writes safe and simple; this suits OLTP systems, the databases behind apps that take orders all day. A denormalized design copies facts into wider tables so reports need fewer or simpler joins; this suits analytics (OLAP), often as a star schema with one fact table and several dimension tables. Many systems use both: a normalized database for the app and a denormalized copy for reports.
In this lesson you will learn:
- what OLTP and OLAP workloads are and why they want different designs
- how to build a star schema (fact and dimension tables) from the shop data
- how to check that the star schema gives exactly the same answers
- why a stored, copied value can drift, and how a materialized view denormalizes in a controlled way
- what EXPLAIN shows (and does not show) when you compare the two designs
Before you start: Lesson 29, Database Normalization: 1NF, 2NF, 3NF and BCNF With Examples and Lesson 23, SQL Views: CREATE VIEW and Materialized Views in PostgreSQL.
We ran every example on PostgreSQL 16.15 with the shop database and checked the current PostgreSQL 18 manual. Everything here works on newer versions too. This lesson builds a small star schema from the shop data and drops it at the end, so the four shop tables stay unchanged.
Table of Contents
OLTP vs OLAP: two different jobs
OLTP (online transaction processing) is the app side: customers sign up, orders come in, statuses change. Microsoft’s architecture guide describes OLTP systems as ones that “record business interactions as they occur”, and its table of traits lists them as “Highly normalized” with “Heavy writes, moderate reads” (Microsoft Learn: OLTP). Our shop database is OLTP: in Lesson 29 we saw that normalization stops update, insert and delete anomalies.
OLAP (online analytical processing) is the report side: revenue by month, best categories, top countries. The same guide says OLAP databases “are optimized for heavy-read and low-write tasks” and “typically use a star or snowflake schema instead of traditional normalization” (Microsoft Learn: OLAP). The OLTP page explains why reports on normalized tables get complex: “most queries need to denormalize the data by using joins” (Microsoft Learn: OLTP).
The question on the normalized tables
Our report question: revenue per quarter and category, for customers in Pakistan, without cancelled orders. On the shop tables it needs all four tables:
SELECT EXTRACT(QUARTER FROM o.order_date) AS quarter, p.category,
SUM(oi.quantity * oi.unit_price) AS revenue
FROM order_items oi
JOIN orders o ON o.id = oi.order_id
JOIN products p ON p.id = oi.product_id
JOIN customers c ON c.id = o.customer_id
WHERE o.status <> 'cancelled' AND c.country = 'Pakistan'
GROUP BY 1, 2
ORDER BY 1, 2;
quarter | category | revenue
---------+-------------+---------
2 | Electronics | 22.99
2 | Stationery | 25.00
3 | Accessories | 45.00
3 | Electronics | 341.99
3 | Home Office | 96.00
3 | Stationery | 118.50
4 | Electronics | 89.00
4 | Stationery | 13.50
(8 rows)
It works, but every report writer must know the join path, remember to multiply quantity by unit price, and work out quarters from dates.
Build a star schema from the shop data
A star schema has one fact table in the middle and dimension tables around it. The Kimball Group, whose books made this design popular, says star schemas “characteristically consist of fact tables linked to associated dimension tables” (Kimball Group: Star schemas and OLAP cubes).

Dimension tables: the who, what and when
Dimension tables describe things. They are usually “wide, flat denormalized tables” (Kimball Group: Dimension table structure). Each gets its own surrogate key, and keeps the shop’s id as a natural key (Lesson 28). Kimball advises “anonymous integer primary keys for every dimension” (Kimball Group: Dimension surrogate keys). We make customer_id UNIQUE because we keep one row per customer; warehouses that keep the history of changes store several rows per natural key. The three tables:
CREATE TABLE dim_customer (
customer_key integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id integer NOT NULL UNIQUE,
name text NOT NULL,
city text,
country text NOT NULL
);
CREATE TABLE dim_product (
product_key integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
product_id integer NOT NULL UNIQUE,
name text NOT NULL,
category text NOT NULL
);
CREATE TABLE dim_date (
date_key integer PRIMARY KEY,
full_date date NOT NULL UNIQUE,
year integer NOT NULL,
quarter integer NOT NULL,
month integer NOT NULL,
month_name text NOT NULL
);
We load them from the shop tables. The date dimension gets one row per day from June to October, made with generate_series (Lesson 22):
INSERT INTO dim_customer (customer_id, name, city, country)
SELECT id, name, city, country FROM customers ORDER BY id;
INSERT INTO dim_product (product_id, name, category)
SELECT id, name, category FROM products ORDER BY id;
INSERT INTO dim_date
SELECT to_char(day, 'YYYYMMDD')::integer, day::date,
EXTRACT(YEAR FROM day), EXTRACT(QUARTER FROM day), EXTRACT(MONTH FROM day),
to_char(day, 'Mon')
FROM generate_series(DATE '2026-06-01', DATE '2026-10-31', INTERVAL '1 day') AS g(day);
SELECT * FROM dim_date WHERE full_date = '2026-09-02';
INSERT 0 10
INSERT 0 10
INSERT 0 153
date_key | full_date | year | quarter | month | month_name
----------+------------+------+---------+-------+------------
20260902 | 2026-09-02 | 2026 | 3 | 9 | Sep
(1 row)
The quarter and month name are worked out once, at load time, instead of in every report.
The fact table: one row per order line
A fact table stores the numbers of a business event. Before you design it, you declare its grain, what one row means; Kimball calls this “the pivotal step in a dimensional design” (Kimball Group: Grain). Our grain: one row per product in an order.
CREATE TABLE fact_sales (
date_key integer NOT NULL REFERENCES dim_date (date_key),
customer_key integer NOT NULL REFERENCES dim_customer (customer_key),
product_key integer NOT NULL REFERENCES dim_product (product_key),
order_id integer NOT NULL,
status text NOT NULL,
quantity integer NOT NULL,
revenue numeric(10,2) NOT NULL,
PRIMARY KEY (order_id, product_key)
);
INSERT INTO fact_sales
SELECT to_char(o.order_date, 'YYYYMMDD')::integer, dc.customer_key, dp.product_key,
o.id, o.status, oi.quantity, oi.quantity * oi.unit_price
FROM order_items oi
JOIN orders o ON o.id = oi.order_id
JOIN dim_customer dc ON dc.customer_id = o.customer_id
JOIN dim_product dp ON dp.product_id = oi.product_id;
SELECT * FROM fact_sales WHERE order_id = 14 ORDER BY product_key;
CREATE TABLE
INSERT 0 40
date_key | customer_key | product_key | order_id | status | quantity | revenue
----------+--------------+-------------+----------+-----------+----------+---------
20260902 | 4 | 1 | 14 | delivered | 1 | 24.99
20260902 | 4 | 2 | 14 | delivered | 1 | 89.00
20260902 | 4 | 4 | 14 | delivered | 1 | 45.00
(3 rows)
All 40 order lines loaded. The revenue column is already multiplied out. The keys equal the shop ids here only because we loaded the rows in id order.
The foreign keys still guard the star. An order from 2 November cannot load, because dim_date stops at 31 October:
INSERT INTO fact_sales VALUES (20261102, 10, 9, 23, 'pending', 1, 259.00);
ERROR: insert or update on table "fact_sales" violates foreign key constraint "fact_sales_date_key_fkey"
DETAIL: Key (date_key)=(20261102) is not present in table "dim_date".
Load jobs add new dates to the date dimension before they load new facts.
Same question, same answer?
The star schema version:
SELECT d.quarter, p.category, SUM(f.revenue) AS revenue
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_customer c ON c.customer_key = f.customer_key
WHERE f.status <> 'cancelled' AND c.country = 'Pakistan'
GROUP BY 1, 2
ORDER BY 1, 2;
quarter | category | revenue
---------+-------------+---------
2 | Electronics | 22.99
2 | Stationery | 25.00
3 | Accessories | 45.00
3 | Electronics | 341.99
3 | Home Office | 96.00
3 | Stationery | 118.50
4 | Electronics | 89.00
4 | Stationery | 13.50
(8 rows)
The same 8 rows. Every join now goes from the fact table straight to one dimension, and nobody has to remember the order path or the revenue formula. One test is not proof, so we compare every quarter, category and country total in both directions with EXCEPT (Lesson 15):
WITH oltp AS (
SELECT EXTRACT(QUARTER FROM o.order_date)::integer AS quarter, p.category, c.country,
SUM(oi.quantity * oi.unit_price) AS revenue
FROM order_items oi
JOIN orders o ON o.id = oi.order_id
JOIN products p ON p.id = oi.product_id
JOIN customers c ON c.id = o.customer_id
WHERE o.status <> 'cancelled'
GROUP BY 1, 2, 3
), star AS (
SELECT d.quarter, p.category, c.country, SUM(f.revenue) AS revenue
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_customer c ON c.customer_key = f.customer_key
WHERE f.status <> 'cancelled'
GROUP BY 1, 2, 3
)
SELECT (SELECT COUNT(*) FROM oltp) AS groups,
(SELECT COUNT(*) FROM (SELECT * FROM oltp EXCEPT SELECT * FROM star) AS a) AS only_in_oltp,
(SELECT COUNT(*) FROM (SELECT * FROM star EXCEPT SELECT * FROM oltp) AS b) AS only_in_star;
groups | only_in_oltp | only_in_star
--------+--------------+--------------
25 | 0 | 0
(1 row)
All 25 groups match. Always run a check like this after you build a reporting copy.
What EXPLAIN shows (and what it does not)
EXPLAIN shows the plan PostgreSQL picks. COSTS OFF hides the cost estimates, so we look only at the shape. Plans depend on table statistics, so we refresh them with ANALYZE first. The OLTP query:
ANALYZE customers, products, orders, order_items, dim_customer, dim_product, dim_date, fact_sales;
EXPLAIN (COSTS OFF)
SELECT EXTRACT(QUARTER FROM o.order_date) AS quarter, p.category,
SUM(oi.quantity * oi.unit_price) AS revenue
FROM order_items oi
JOIN orders o ON o.id = oi.order_id
JOIN products p ON p.id = oi.product_id
JOIN customers c ON c.id = o.customer_id
WHERE o.status <> 'cancelled' AND c.country = 'Pakistan'
GROUP BY 1, 2;
ANALYZE
QUERY PLAN
----------------------------------------------------------------------------
HashAggregate
Group Key: EXTRACT(quarter FROM o.order_date), p.category
-> Hash Join
Hash Cond: (oi.product_id = p.id)
-> Hash Join
Hash Cond: (oi.order_id = o.id)
-> Seq Scan on order_items oi
-> Hash
-> Hash Join
Hash Cond: (o.customer_id = c.id)
-> Seq Scan on orders o
Filter: (status <> 'cancelled'::text)
-> Hash
-> Seq Scan on customers c
Filter: (country = 'Pakistan'::text)
-> Hash
-> Seq Scan on products p
(17 rows)
And the star query (same text as above, with EXPLAIN (COSTS OFF) in front):
QUERY PLAN
----------------------------------------------------------------------------
HashAggregate
Group Key: d.quarter, p.category
-> Hash Join
Hash Cond: (f.product_key = p.product_key)
-> Hash Join
Hash Cond: (d.date_key = f.date_key)
-> Seq Scan on dim_date d
-> Hash
-> Hash Join
Hash Cond: (f.customer_key = c.customer_key)
-> Seq Scan on fact_sales f
Filter: (status <> 'cancelled'::text)
-> Hash
-> Seq Scan on dim_customer c
Filter: (country = 'Pakistan'::text)
-> Hash
-> Seq Scan on dim_product p
(17 rows)
Read them from the inside out: filter customers, join them to the main table, then join the other tables, then group. Both plans have three hash joins. The star schema did not remove joins here; it made them simpler (one hop each, on a key) and moved the date and revenue work to load time. With 40 rows there is nothing meaningful to time, so this lesson makes no speed claim. The manual warns that plan numbers “depend on the actual contents of the tables involved” (PostgreSQL docs: EXPLAIN); Lesson 32 covers reading plans.
The risk of denormalizing: copies drift
Denormalizing inside the OLTP database is where trouble starts. Say we store each order’s total in a copy of orders, and then a quantity changes (inside a transaction we roll back, as in Lesson 19):
CREATE TABLE orders_with_total AS
SELECT o.id, o.customer_id, o.order_date, o.status,
SUM(oi.quantity * oi.unit_price) AS total
FROM orders o
JOIN order_items oi ON oi.order_id = o.id
GROUP BY o.id;
BEGIN;
UPDATE order_items SET quantity = 3 WHERE order_id = 1 AND product_id = 6;
SELECT t.id, t.total AS stored_total, SUM(oi.quantity * oi.unit_price) AS real_total
FROM orders_with_total t
JOIN order_items oi ON oi.order_id = t.id
GROUP BY t.id, t.total
HAVING t.total <> SUM(oi.quantity * oi.unit_price);
ROLLBACK;
SELECT 22
BEGIN
UPDATE 1
id | stored_total | real_total
----+--------------+------------
1 | 47.99 | 60.49
(1 row)
ROLLBACK
The stored 47.99 is now wrong. This is the update anomaly from Lesson 29, created on purpose. Every copy needs a plan to keep it in sync.
A materialized view: controlled denormalization
A materialized view (Lesson 23) is a safer way to denormalize. It is a wide, flat copy, but PostgreSQL rebuilds it from the normalized tables whenever you run REFRESH MATERIALIZED VIEW, so it never holds facts of its own:
CREATE MATERIALIZED VIEW sales_wide AS
SELECT o.id AS order_id, o.order_date, o.status,
c.name AS customer, c.country,
p.name AS product, p.category,
oi.quantity, oi.quantity * oi.unit_price AS revenue
FROM order_items oi
JOIN orders o ON o.id = oi.order_id
JOIN customers c ON c.id = o.customer_id
JOIN products p ON p.id = oi.product_id;
SELECT category, SUM(revenue) AS revenue
FROM sales_wide
WHERE status <> 'cancelled'
GROUP BY category
ORDER BY revenue DESC;
SELECT 40
category | revenue
-------------+---------
Electronics | 1478.21
Stationery | 283.00
Home Office | 160.00
Accessories | 135.00
(4 rows)
No joins in the report query. The data is only as fresh as the last refresh.
Normalization vs denormalization: trade-offs
| normalized (OLTP) | denormalized (star schema, wide view) | |
|---|---|---|
| each fact stored | once | many times |
| writes | simple and safe | need a load or refresh job |
| report queries | more joins, more logic | fewer or simpler joins |
| risk | complex reports | stale or drifting copies |
| typical user | the application | analysts and dashboards |
Denormalize when reports are slow or hard to write and the data can be a little old. Keep the normalized tables as the source of truth, build the copy from them, and test it with EXCEPT.
Try it yourself
Exercise 1: Stationery units per month
From the star schema, show units of Stationery sold per month (number and name), without cancelled orders.
Exercise 2: Check it against OLTP
Write the same question on the shop tables and count the differences with EXCEPT.
Exercise 3: Top 3 countries
From sales_wide, show the top 3 countries by revenue, without cancelled orders.
Solutions
Solution 1
SELECT d.month, d.month_name, SUM(f.quantity) AS units
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
WHERE p.category = 'Stationery' AND f.status <> 'cancelled'
GROUP BY d.month, d.month_name
ORDER BY d.month;
month | month_name | units
-------+------------+-------
6 | Jun | 2
7 | Jul | 9
8 | Aug | 8
9 | Sep | 6
10 | Oct | 5
(5 rows)
Grouping by month keeps the months in calendar order.
Solution 2
SELECT COUNT(*) AS differences
FROM (
(SELECT EXTRACT(MONTH FROM o.order_date)::integer AS month, SUM(oi.quantity) AS units
FROM order_items oi
JOIN orders o ON o.id = oi.order_id
JOIN products p ON p.id = oi.product_id
WHERE p.category = 'Stationery' AND o.status <> 'cancelled'
GROUP BY 1
EXCEPT
SELECT d.month, SUM(f.quantity)
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
WHERE p.category = 'Stationery' AND f.status <> 'cancelled'
GROUP BY 1)
) AS diff;
differences
-------------
0
(1 row)
Zero differences in this direction; swap the two halves to check the other.
Solution 3
SELECT country, SUM(revenue) AS revenue
FROM sales_wide
WHERE status <> 'cancelled'
GROUP BY country
ORDER BY revenue DESC
LIMIT 3;
country | revenue
----------+---------
Pakistan | 751.98
Italy | 412.48
Canada | 244.46
(3 rows)
When you finish, drop the practice objects:
DROP MATERIALIZED VIEW sales_wide;
DROP TABLE orders_with_total;
DROP TABLE fact_sales, dim_date, dim_product, dim_customer;
DROP MATERIALIZED VIEW
DROP TABLE
DROP TABLE
Common mistakes
- Denormalizing the OLTP tables first. A stored total drifted from 47.99 to a real 60.49 after one update. Build reporting copies beside the source, not inside it.
- Not covering new dates in the date dimension.
violates foreign key constraint "fact_sales_date_key_fkey". Extenddim_datebefore loading facts. - Mixing grains in one fact table. Kimball warns that “different grains must not be mixed in the same fact table”. Order lines and daily totals belong in separate tables.
- Claiming speed from a tiny test. With 40 rows, timings tell you nothing;
EXPLAIN (COSTS OFF)shows the plan shape, not the time. - Skipping the comparison. Check every reporting copy against the source with
EXCEPT, as we did for all 25 groups.
Frequently asked questions
When should you denormalize a database?
When reports are hard to write or slow on the normalized tables, and readers can accept data that is a little old. Keep the normalized tables as the source of truth and build the denormalized copy from them, with a materialized view or a scheduled load.
Is a star schema normalized or denormalized?
The fact table is narrow: it holds the dimension keys and the numbers (measures), plus small codes such as the order number and status (Kimball Group: Fact table structure). The dimension tables are usually denormalized: dim_product keeps the category name right in the row. A snowflake schema splits dimensions into more linked tables, which Kimball advises against (Kimball Group: Snowflaked dimensions).
Can OLTP and OLAP run in the same database?
Yes, and for small systems like our shop that is normal. Microsoft’s guide notes that most workloads are mixed and calls this HTAP (hybrid transactional and analytical processing). As data grows, heavy reports are often moved to a separate warehouse, as in the data engineering projects list.
Summary
- OLTP systems are normalized for many small, safe writes; OLAP systems are read-heavy and often use a star schema.
- A star schema has a fact table (numbers at a declared grain) and flat dimension tables (who, what, when) with surrogate keys.
- Always prove a reporting copy gives the same results, for example with
EXCEPTin both directions. - Copied values inside OLTP tables can drift; a materialized view is a controlled denormalization that you refresh.
EXPLAIN (COSTS OFF)shows plan shape; never claim a speed win from a tiny dataset.
Next lesson
Next: Lesson 31, How SQL Indexes Work: B-tree, Composite, Covering and Partial Indexes.
Sources
- Microsoft Learn: Online transaction processing (OLTP)
- Microsoft Learn: Online analytical processing (OLAP)
- Kimball Group: Star schemas and OLAP cubes
- Kimball Group: Grain
- Kimball Group: Dimension table structure
- Kimball Group: Dimension surrogate keys
- Kimball Group: Fact table structure
- Kimball Group: Snowflaked dimensions
- PostgreSQL documentation: EXPLAIN
- PostgreSQL documentation: CREATE MATERIALIZED VIEW





