Developer Guides, Cheat Sheets & Tools

SQL course - Part 11: DESIGN

Part index Prerequisites Previous Next Full course

πŸ“ PART 11 β€” DESIGN


51. Normalization, 1NF to BCNF

🎚️ Level ⏱️ Time 🎯 After this chapter you can…
🟒🟑 Beginner–Intermediate 35 min Spot badly designed tables Β· Apply 1NF, 2NF, and 3NF step by step Β· Design tables where every fact lives in one place

[!NOTE] πŸ“Œ In plain words: Normalization is the process of organizing your tables so that every fact is stored in exactly one place. Do it well and updates are simple and safe. Do it badly and your data contradicts itself.

🌍 Analogy: Writing your home address on 50 different forms. Move house, and you must find and correct all 50 β€” and you will miss some. Normalization means writing it once, and everything else pointing at that one copy.

51.1 πŸ’₯ The three anomalies normalization prevents

Start with an unnormalized table:

order_id customer_name customer_email customer_city products total
1001 Amara Silva amara@ex.com Colombo Laptop, Mouse 1544.00
1002 Amara Silva amara@ex.com Colombo Keyboard 129.00
1003 John Baker john@ex.com London Phone, Buds 1078.00
Anomaly What goes wrong Example
Update anomaly The same fact stored many times; fix one and miss the rest Amara changes email β†’ must update every one of her order rows
Insert anomaly You cannot record one fact without inventing another You cannot add a new customer until they place an order
Delete anomaly Deleting one fact destroys an unrelated one Delete order 1003 and John Baker vanishes from the system entirely

Plus the products column holding 'Laptop, Mouse' makes it impossible to answer β€œhow many laptops did we sell?” without string parsing.

51.2 1️⃣ First Normal Form (1NF)

Rule: every cell holds a single value that cannot be split further (atomic), and there are no repeating groups of columns.

❌ Violates 1NF β€” multiple values in one cell:

order_id products
1001 Laptop, Mouse, Keyboard

❌ Also violates 1NF β€” repeating groups as columns:

order_id product_1 product_2 product_3
1001 Laptop Mouse Keyboard

(What happens on the day someone orders four items?)

βœ… 1NF β€” one row per value:

order_id product_id quantity
1001 1 1
1001 12 2
1001 11 1

[!TIP] πŸ’‘ How to spot a 1NF violation in the wild: a column containing commas, a column named phone1, phone2, phone3, or a query that needs SUBSTRING to find a value. Any of those means the model is fighting you.

51.3 2️⃣ Second Normal Form (2NF)

Rule: be in 1NF, and every non-key column must depend on the whole primary key β€” not just part of it.

(This only ever matters when the primary key is made of more than one column β€” a *composite key.)*

❌ Violates 2NF:

order_id (PK) product_id (PK) quantity product_name product_price
1001 5 2 Zenith Phone 12 899.00
1002 5 1 Zenith Phone 12 899.00

product_name depends only on product_id, not on the full key (order_id, product_id). So it is repeated for every order containing that product β€” and if the name changes, you must update it everywhere.

βœ… 2NF β€” split it out:

order_items(order_id, product_id, quantity, unit_price)   -- unit_price = the price PAID
products(product_id, product_name, unit_price)             -- unit_price = the price TODAY

[!TIP] πŸ’‘ Note unit_price stays in order_items. That is not a violation β€” it is the price at the time of sale, which genuinely depends on the specific order line. products.unit_price is the current price. Two different facts, correctly stored separately.

51.4 3️⃣ Third Normal Form (3NF)

Rule: be in 2NF, and no non-key column may depend on another non-key column (no transitive dependency β€” a chain where the key decides A, and A decides B).

❌ Violates 3NF:

customer_id (PK) full_name city country country_dial_code
1 Amara Silva Colombo Sri Lanka +94
2 John Baker London UK +44

country_dial_code depends on country, which is not the key. Every Sri Lankan customer repeats +94. If the code changed, you would update thousands of rows.

βœ… 3NF:

customers(customer_id, full_name, city, country_code)
countries(country_code, country_name, dial_code)

[!TIP] πŸ’‘ The classic mnemonic for 3NF: β€œEvery non-key column must depend on the key (1NF), the whole key (2NF), and nothing but the key (3NF) β€” so help me Codd.” (Edgar F. Codd invented the relational database model.)

51.5 πŸ”’ BCNF and beyond

BCNF (Boyce-Codd Normal Form) is a stricter 3NF: any column that decides another column’s value (a determinant) must on its own be able to identify a row uniquely (a candidate key). It only matters in the unusual case where a table has several overlapping candidate keys.

4NF removes independent multi-valued facts stored together. If an employee has many skills and many languages, storing both in one table forces you to pair every skill with every language, which means nothing. Split into employee_skills and employee_languages.

5NF deals with join dependencies. You will almost never meet it in practice.

[!IMPORTANT] 🎯 In real-world practice: 3NF is the target. Reaching 3NF eliminates virtually every anomaly that causes real pain. BCNF and above are worth knowing for interviews and for the rare edge case, but a well-designed 3NF design is what real systems run on.

51.6 πŸ—οΈ Normalizing ShopDB β€” a worked example

❌ The flat, unnormalized version:

CREATE TABLE orders_flat (
    order_id        INT,
    customer_name   VARCHAR(100),
    customer_email  VARCHAR(150),
    customer_city   VARCHAR(60),
    customer_country VARCHAR(60),
    order_date      DATE,
    product_names   VARCHAR(500),      -- ❌ 1NF: comma-separated
    quantities      VARCHAR(100),      -- ❌ 1NF: comma-separated
    total           DECIMAL(10,2)      -- ❌ derivable; can drift out of sync
);

βœ… Normalized to 3NF β€” which is exactly the ShopDB you built in Chapter 4:

customers   (customer_id PK, full_name, email, city, country, ...)
             └── one row per customer, email stored ONCE

categories  (category_id PK, category_name, description)
suppliers   (supplier_id PK, company_name, country, ...)

products    (product_id PK, product_name, category_id FK, supplier_id FK, unit_price, ...)
             └── product name stored ONCE

orders      (order_id PK, customer_id FK, employee_id FK, order_date, status, ...)
             └── one row per order; no customer details duplicated

order_items (order_id FK, product_id FK, unit_price, quantity, discount)
             └── PK (order_id, product_id) β€” one row per line, fully atomic

payments    (payment_id PK, order_id FK, amount, method, status)

Notice what disappeared: the total column. It is derivable from order_items, so storing it risks the stored total disagreeing with the sum of the lines. Compute it when you need it:

SELECT order_id, SUM(unit_price * quantity * (1 - discount)) AS total
FROM order_items GROUP BY order_id;

51.7 🧭 The practical normalization checklist

Ask these questions of every table you design:

  1. β˜‘οΈ Does any cell contain a list, or a comma?
  2. β˜‘οΈ Do I have columns like x1, x2, x3?
  3. β˜‘οΈ Is the same text repeated across many rows?
  4. β˜‘οΈ If I updated one fact, would I have to change more than one row?
  5. β˜‘οΈ Can I add a new β€œthing” without inventing a fake related record?
  6. β˜‘οΈ If I deleted a row, would I lose an unrelated fact forever?
  7. β˜‘οΈ Does any non-key column depend on another non-key column?
  8. β˜‘οΈ Am I storing something I could always calculate?

[!TIP] πŸ’‘ A β€œyes” to any of 1–7 means you have more normalizing to do. A β€œyes” to 8 means you should either remove it or read the next chapter deliberately.

51.8 πŸ§ͺ Try it yourself

  1. Take the orders_flat table above and normalize it to 3NF on paper, then in SQL.
  2. Find the 3NF violation in this table and fix it: employees(employee_id, name, department_id, department_name, department_budget).
  3. Design a schema for a school: students, courses, enrolments, teachers, grades. Get it to 3NF.
  4. Explain in one sentence why order_items.unit_price is not a normalization violation.

🧭 In practice β€” normalization

How to use it. Apply the forms in order. 1NF: one value per cell, no repeating groups. 2NF: every non-key column depends on the whole key. 3NF: and on nothing but the key. BCNF: tightens 3NF for overlapping candidate keys. Expected result: every fact stored exactly once, so it can be corrected in exactly one place.

When to use it. When designing any transactional (OLTP) schema, and when diagnosing data that has gone inconsistent.

Where to use it. The write side of a system. Scenario: the customer’s email stored on every order row. One typo on one order creates a second version of the truth, and no query can tell you which is correct. Moving email to customers and referencing it by key makes that failure impossible β€” this is the update anomaly that normalization exists to prevent.

When not to use it. Do not normalise a reporting or analytics schema to 3NF β€” a star schema (Chapter 53) deliberately denormalises for query speed, and that is correct, not sloppy. Do not normalise past the point of comprehensibility either: 5NF and 6NF are real and are almost never worth it in a business system.

Best practices. Aim for 3NF as the default and denormalise deliberately, with a reason you can state, rather than by accident (Chapter 52). Remember that storing an order’s price at time of sale is not a normalization failure β€” the price on the order and the current product price are genuinely different facts, and conflating them is the actual bug.


52. Denormalization and when to break the rules

🎚️ Level ⏱️ Time 🎯 After this chapter you can…
🟑 Intermediate 20 min Know when storing data twice is worth it · Use the five safe patterns · Keep duplicated data honest

[!NOTE] πŸ“Œ In plain words: Denormalization is deliberately storing something twice to make reads faster. It is not a mistake β€” it is a trade, and you must know exactly what you are trading.

🌍 Analogy: Keeping a spare key at your neighbour’s house. Strictly, there should be one key. But retrieving it is so much faster than calling a locksmith that the duplication is worth it β€” as long as you remember to update both when you change the lock.

52.1 βš–οΈ The trade

You gain You pay
⚑ Faster reads (fewer joins) ⚠️ More storage
πŸ“Š Simpler report queries ⚠️ Slower writes (multiple places to update)
πŸ›‘οΈ Fewer locks on busy tables πŸ› Risk of the copies disagreeing

[!WARNING] ⚠️ The last one is the real cost. Every denormalized copy is a promise you have to keep, forever, in every code path. If a single UPDATE somewhere forgets to maintain it, your data starts lying and nobody notices for months.

52.2 🎯 The five legitimate denormalization patterns

β‘  Historical snapshot values β€” the one everybody needs

-- βœ… order_items.unit_price duplicates products.unit_price ON PURPOSE
-- The order must remember what the customer ACTUALLY paid, forever.
-- If the product price rises tomorrow, last year's invoices must not change.

[!TIP] πŸ’‘ This is not really denormalization at all β€” it is recognizing that β€œthe price now” and β€œthe price paid on 3 March” are two different facts. Any e-commerce, invoicing, or accounting system must store both. Also applies to: shipping addresses on orders, tax rates on invoices, product names on receipts.

β‘‘ Pre-computed aggregates

-- βœ… Store a running count that would otherwise need a COUNT(*) on millions of rows
ALTER TABLE customers ADD order_count INT NOT NULL DEFAULT 0;
ALTER TABLE customers ADD lifetime_value DECIMAL(12,2) NOT NULL DEFAULT 0;

-- Maintained by a trigger, a stored procedure, or a nightly job

[!IMPORTANT] 🎯 When it is worth it: a leaderboard, a β€œposts: 4,281” counter, a dashboard read thousands of times per minute where the underlying COUNT scans a huge table. When it is not: anything you can compute in under 50 ms on demand.

β‘’ Redundant columns to avoid a join

-- βœ… Copy the customer's country onto the order so reports skip a join
ALTER TABLE orders ADD customer_country VARCHAR(60);

[!WARNING] ⚠️ But this one is also a snapshot decision in disguise. If the customer moves to a new country, should last year’s orders change country? Almost certainly not β€” so this copy is actually correct history, not stale data. Think it through explicitly.

β‘£ Summary and reporting tables

-- βœ… πŸŸ₯ MSSQL (in MySQL, make refreshed_at a DATETIME) β€” rebuild nightly; dashboards read this instead of hammering the live tables
CREATE TABLE daily_sales_summary (
    sales_date      DATE PRIMARY KEY,
    order_count     INT NOT NULL,
    total_revenue   DECIMAL(14,2) NOT NULL,
    unique_customers INT NOT NULL,
    refreshed_at    DATETIME2(0) NOT NULL
);

[!TIP] πŸ’‘ This is the safest denormalization, because the summary table is derived and disposable. If it drifts, you rebuild it from the source of truth. No data is ever lost. Prefer this pattern over adding redundant columns to your live tables.

β‘€ Star schemas for analytics β€” see the next chapter.

52.3 πŸ›‘οΈ Keeping denormalized data honest

Whatever you denormalize, you need all three of these:

-- πŸŸ₯ MSSQL
-- 1️⃣ MAINTAIN it β€” a trigger, procedure, or job that keeps it current
CREATE OR ALTER TRIGGER trg_update_customer_stats
ON orders
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
    SET NOCOUNT ON;

    UPDATE c
    SET c.order_count = COALESCE(x.n, 0)
    FROM customers c
    LEFT JOIN (SELECT customer_id, COUNT(*) AS n FROM orders GROUP BY customer_id) x
      ON x.customer_id = c.customer_id
    WHERE c.customer_id IN (SELECT customer_id FROM inserted
                            UNION SELECT customer_id FROM deleted);
END;
GO

-- 2️⃣ VERIFY it β€” a reconciliation query you run on a schedule
SELECT
    c.customer_id,
    c.order_count       AS stored_count,
    COUNT(o.order_id)   AS actual_count
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.customer_id, c.order_count
HAVING c.order_count <> COUNT(o.order_id);      -- should return ZERO rows

-- 3️⃣ REBUILD it β€” a script that recomputes everything from the source of truth
UPDATE c SET order_count = COALESCE(s.n, 0)
FROM customers c
LEFT JOIN (SELECT customer_id, COUNT(*) AS n FROM orders GROUP BY customer_id) s
  ON s.customer_id = c.customer_id;

[!TIP] πŸ’‘ If you cannot write the verification query, you are not ready to denormalize. Put that reconciliation query in a scheduled job and alert on any rows it returns. Silent data drift is the entire danger, and this is how you make it loud.

52.4 πŸ“ The decision rule

Is the query genuinely too slow?
  └─ No  β†’ πŸ›‘ STOP. Do not denormalize. You are optimizing a non-problem.
  └─ Yes ↓

Have you added the right indexes?
  └─ No  β†’ 🎯 Do that first. It solves this 80% of the time.
  └─ Yes ↓

Can a materialized view / summary table solve it? (derived, disposable, safe)
  └─ Yes β†’ βœ… Do that.
  └─ No  ↓

Is this genuinely a HISTORICAL SNAPSHOT rather than duplication?
  └─ Yes β†’ βœ… Store it. It is a separate fact, not a copy.
  └─ No  ↓

Can you write the maintenance, verification, AND rebuild scripts?
  └─ No  β†’ πŸ›‘ STOP.
  └─ Yes β†’ βœ… Denormalize, and document exactly why in a comment.

[!TIP] πŸ’‘ β€œNormalize until it hurts, denormalize until it works.” Start normalized. Measure. Denormalize only where the numbers prove you must, and never without the three safeguards above.

52.5 πŸ§ͺ Try it yourself

  1. Add an order_count column to customers, populate it, and write the verification query.
  2. Deliberately insert an order without updating the counter, then run your verification query and see it catch the drift.
  3. Build a daily_sales_summary table and a refresh script.
  4. List three columns in ShopDB that look denormalized but are actually correct historical snapshots.

🧭 In practice β€” denormalization

How to use it. Deliberately store something twice β€” a cached total, a copied name, a pre-joined summary table β€” and then take explicit responsibility for keeping the copies in step. Expected result: faster reads, in exchange for more expensive writes and a new consistency risk you have chosen and documented.

When to use it. When you have measured a read problem that normalisation causes and no index or query rewrite fixes it, and when a historical fact must be frozen as it was.

Where to use it. Reporting layers and high-read systems. Scenario: a dashboard joins six tables on every page load. A nightly summary table reduces that to one indexed read. The trade is that the dashboard is up to a day stale β€” which is usually fine, and must be stated rather than discovered.

When not to use it. Do not denormalise before measuring. It is the classic premature optimisation: you take on permanent complexity and a permanent risk of divergence, to fix a problem an index would have solved. Do not denormalise data that must be immediately consistent β€” account balances, stock levels β€” unless you are prepared to maintain it transactionally.

Best practices. Write down how each copy is kept in step: a trigger, a scheduled job, application code, or a materialised view. Then write the reconciliation query that detects divergence, and run it regularly β€” duplicated data drifts, and finding out from a customer is the expensive way. Treat β€œprice at time of sale” as a different category: that is not a copy, it is a separate fact that happens to have started equal.


53. Data modeling and the star schema

🎚️ Level ⏱️ Time 🎯 After this chapter you can…
🟑 Intermediate 30 min Plan tables before writing SQL · Model one-to-many and many-to-many links · Build a star schema for reports · Keep history when data changes

[!NOTE] πŸ“Œ In plain words: Data modeling is designing the tables before you write any SQL. Get it right and everything that comes after is easy; get it wrong and you fight it for years.

🌍 Analogy: An architect’s drawing of a house. Moving a wall on paper costs an eraser. Moving it after the house is built costs a fortune.

53.1 🧭 The three levels of a data model

Level Audience Contains
Conceptual Business people The main things (entities) and how they relate. No columns, no types. β€œCustomers place Orders for Products.”
Logical Analysts and architects Every column, key, and relationship, normalized. Not tied to any database product.
Physical Developers and DBAs (database administrators) Actual CREATE TABLE statements: types, indexes, partitions, engine-specific details.

53.2 πŸ”— Modelling relationships correctly

One-to-many β€” the most common. Put the foreign key on the many side.

One customer β†’ many orders. The FK lives on orders:
    orders.customer_id  ──►  customers.customer_id

Many-to-many β€” always needs a bridge (junction) table.

-- One order has many products; one product is on many orders.
-- (Named _demo so it does not clash with the real ShopDB order_items table.)
CREATE TABLE order_items_demo (
    order_id   INT NOT NULL,
    product_id INT NOT NULL,
    quantity   INT NOT NULL,
    unit_price DECIMAL(10,2) NOT NULL,
    PRIMARY KEY (order_id, product_id)
);

[!TIP] πŸ’‘ A bridge table is often more than plumbing. order_items carries quantity, unit_price, and discount β€” real facts that belong to the relationship, not to either side. When you find yourself asking β€œwhere do I put the quantity?”, the bridge table is the answer.

One-to-one β€” rarer. Use it to split off optional or sensitive columns.

-- Keep sensitive data in a separate table with tighter permissions
CREATE TABLE customer_private (
    customer_id   INT PRIMARY KEY,
    national_id   VARCHAR(50),
    date_of_birth DATE,
    CONSTRAINT fk_cp_customer FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);

Self-referencing β€” hierarchies.

employees.manager_id           ──►  employees.employee_id
categories.parent_category_id  ──►  categories.category_id

53.3 ⭐ The star schema β€” modelling for analytics

[!NOTE] πŸ“Œ In plain words: Normalized designs (3NF) are built for writing β€” one fact in one place. Reporting needs fast reading β€” millions of rows summarized quickly. The star schema is the standard design for reporting: one big fact table of events (each sale) in the middle, surrounded by small dimension tables that describe them (when, who, what).

                  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                  β”‚  dim_date    β”‚
                  β”‚ date_key PK  β”‚
                  β”‚ year, month  β”‚
                  β”‚ quarter, day β”‚
                  β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜
                         β”‚
  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
  β”‚dim_customerβ”‚   β”‚   FACT_SALES       β”‚   β”‚ dim_product  β”‚
  β”‚customer_keyβ”œβ”€β”€β–Ίβ”‚ date_key      FK   │◄─── product_key  β”‚
  β”‚ name, city β”‚   β”‚ customer_key  FK   β”‚   β”‚ name, categoryβ”‚
  β”‚ country    β”‚   β”‚ product_key   FK   β”‚   β”‚ supplier      β”‚
  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚ employee_key  FK   β”‚   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                   β”‚ ─────────────────  β”‚
  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚ quantity   MEASURE β”‚
  β”‚dim_employeeβ”œβ”€β”€β–Ίβ”‚ unit_price MEASURE β”‚
  β”‚employee_keyβ”‚   β”‚ discount   MEASURE β”‚
  β”‚ name, dept β”‚   β”‚ net_amount MEASURE β”‚
  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Β  Fact table Dimension table
Contains Measurements and foreign keys Descriptive attributes
Size Huge (millions to billions of rows) Small (hundreds to millions)
Grows Constantly, by insert Slowly
Example columns quantity, net_amount product_name, country, month_name
Normalized? Yes, by nature Deliberately denormalized (flat)
-- βœ… Works in BOTH: a star schema for ShopDB analytics
CREATE TABLE dim_date (
    date_key     INT PRIMARY KEY,          -- 20260615
    full_date    DATE NOT NULL,
    day_of_month INT NOT NULL,
    month_num    INT NOT NULL,
    month_name   VARCHAR(20) NOT NULL,
    quarter      INT NOT NULL,
    year_num     INT NOT NULL,
    day_name     VARCHAR(20) NOT NULL,
    is_weekend   TINYINT NOT NULL
);

CREATE TABLE dim_customer (
    customer_key  INT PRIMARY KEY,
    customer_id   INT NOT NULL,            -- the original operational key
    full_name     VARCHAR(100) NOT NULL,
    city          VARCHAR(60),
    country       VARCHAR(60) NOT NULL,
    loyalty_tier  VARCHAR(10) NOT NULL
);

CREATE TABLE dim_product (
    product_key   INT PRIMARY KEY,
    product_id    INT NOT NULL,
    product_name  VARCHAR(120) NOT NULL,
    category_name VARCHAR(50) NOT NULL,    -- πŸ”‘ flattened: no join to categories
    supplier_name VARCHAR(100),            -- πŸ”‘ flattened: no join to suppliers
    unit_price    DECIMAL(10,2) NOT NULL
);

CREATE TABLE fact_sales (
    sales_key     BIGINT PRIMARY KEY,
    date_key      INT NOT NULL,
    customer_key  INT NOT NULL,
    product_key   INT NOT NULL,
    employee_key  INT NULL,
    order_id      INT NOT NULL,
    quantity      INT NOT NULL,
    unit_price    DECIMAL(10,2) NOT NULL,
    discount      DECIMAL(4,3) NOT NULL,
    net_amount    DECIMAL(12,2) NOT NULL   -- pre-computed for speed
);

Why analysts love this:

-- Every business question is the same simple shape: fact JOIN dims, GROUP BY
SELECT
    d.year_num,
    d.quarter,
    p.category_name,
    c.country,
    SUM(f.net_amount) AS revenue,
    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
JOIN dim_customer c ON c.customer_key = f.customer_key
GROUP BY d.year_num, d.quarter, p.category_name, c.country
ORDER BY revenue DESC;

[!TIP] πŸ’‘ No nested joins, no chains through three lookup tables β€” every dimension is exactly one join from the fact. That predictable shape is why BI (business intelligence) tools such as Power BI, Tableau, and Looker all expect a star schema.

πŸ”€ Star vs snowflake: a snowflake schema normalizes the dimensions (so dim_product would join to a separate dim_category). It saves a little space and costs extra joins on every query. Prefer the star. Dimension tables are small; the storage saving is not worth the complexity.

53.4 πŸ•°οΈ Slowly Changing Dimensions (SCD)

[!NOTE] πŸ“Œ The question: a customer moves from Colombo to Kandy. Should last year’s sales report now say Kandy? A slowly changing dimension is a descriptive table whose values change now and then, and the β€œtype” is how you handle that change.

Type Behaviour Use when
Type 0 Never changes Date of birth, original signup date
Type 1 Overwrite; history is lost Fixing a typo in a name
Type 2 Add a new row with validity dates; full history kept The important one. Customer moves, changes tier, changes segment
Type 3 Keep a previous_value column You only ever need the prior value
-- βœ… Type 2: the standard implementation
CREATE TABLE dim_customer_scd2 (
    customer_key   INT PRIMARY KEY,        -- surrogate key, NEW for each version
    customer_id    INT NOT NULL,           -- stable business key
    full_name      VARCHAR(100) NOT NULL,
    city           VARCHAR(60),
    country        VARCHAR(60) NOT NULL,
    loyalty_tier   VARCHAR(10) NOT NULL,
    valid_from     DATE NOT NULL,
    valid_to       DATE NULL,              -- NULL = this is the current version
    is_current     TINYINT NOT NULL DEFAULT 1
);
customer_key customer_id city valid_from valid_to is_current
101 1 Colombo 2024-02-11 2026-06-30 0
205 1 Kandy 2026-07-01 NULL 1

Because fact_sales stores the customer_key (not customer_id), every historical sale stays attached to the version of the customer that was true at the time. A 2025 report still says Colombo. That is the whole point.

πŸ”€ MSSQL has this built in as temporal tables:

-- πŸŸ₯ MSSQL
CREATE TABLE customers_temporal (
    customer_id INT PRIMARY KEY,
    full_name   NVARCHAR(100) NOT NULL,
    city        NVARCHAR(60),
    valid_from  DATETIME2 GENERATED ALWAYS AS ROW START,
    valid_to    DATETIME2 GENERATED ALWAYS AS ROW END,
    PERIOD FOR SYSTEM_TIME (valid_from, valid_to)
) WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.customers_history));

-- Then query any point in time:
SELECT * FROM customers_temporal FOR SYSTEM_TIME AS OF '2026-03-01';

This is one of SQL Server’s genuinely excellent features. MySQL has no equivalent β€” you implement SCD Type 2 by hand.

πŸ”Ž Chapter 62 is the full treatment β€” creating and querying temporal tables, retention, Change Tracking for ETL, and the MySQL trigger-based equivalent.

53.5 βœ… The design review checklist

β˜‘οΈ Check
☐ Every table has a primary key
☐ Primary keys are narrow and stable (INT/BIGINT, never updated)
☐ Every relationship has a foreign key constraint
☐ Every foreign key column is indexed (especially in MSSQL)
☐ Column names are consistent (customer_id everywhere, never custID here and cust_id there)
☐ NOT NULL is the default; every nullable column is justified
☐ Money is DECIMAL, never FLOAT
☐ Date-times are stored in UTC (world standard time, with no time-zone shifts)
☐ No comma-separated lists in any column
☐ No column1, column2, column3 patterns
☐ Business rules are enforced by constraints, not only by the app
☐ Every denormalized value has a maintenance and verification plan
☐ Audit columns (created_at, updated_at) exist where they matter
☐ Soft-delete strategy decided consistently across the schema
☐ Naming convention documented and followed everywhere

53.6 πŸ§ͺ Try it yourself

  1. Draw the conceptual model for a library: members, books, copies, loans, reservations, fines.
  2. Turn it into a 3NF logical model, then a physical one with real CREATE TABLE statements.
  3. Build a star schema for ShopDB sales and load it from the operational tables.
  4. Implement SCD Type 2 for dim_customer and simulate a customer moving city.
  5. Run the design review checklist against your library schema.

🧭 In practice β€” data modelling and the star schema

How to use it. Separate facts (measurable events β€” a sale, with its quantities and amounts) from dimensions (the descriptive things you slice by β€” date, product, customer, store). One central fact table joins to several wide, denormalised dimension tables. Expected result: analytical queries with few joins, which business-intelligence tools can navigate without help.

When to use it. When building a reporting database or warehouse, as distinct from the transactional database that runs the application.

Where to use it. Analytics. Scenario: β€œrevenue by category by month by region” against a star schema is one join per dimension. Against a fully normalised OLTP schema it is six or seven joins, and the query is both slower and much harder for an analyst to write correctly.

When not to use it. Do not use a star schema for the transactional system itself β€” its denormalised dimensions make writes and updates awkward and risk exactly the anomalies Chapter 51 warns about. And do not build a warehouse at all for a small application; a few well-indexed reporting views are usually enough, and a warehouse is a system that needs its own maintenance.

Best practices. Decide early how dimensions handle change. Slowly Changing Dimension Type 2 β€” valid_from, valid_to, is_current, where a change closes the old row and inserts a new one β€” is what lets a report about last March still show March’s category names rather than today’s. Getting that wrong means historical reports silently change every time someone renames a product.


βœ… Checkpoint β€” after Chapter 53 Β· you can make it fast, and design it properly

[!IMPORTANT] Performance and design are the two areas where confident-sounding advice is most often wrong. The test for this part is whether you can say why, and what it costs.

πŸ—£οΈ Teach it back

What is it? Why does it matter? How does it work? Can I give an example? β€” for each of:

  • Indexes, and why they are not free (Ch 46)
  • Execution plans as evidence (Ch 47)
  • SARGability (Ch 48)
  • Statistics and parameter sniffing (Ch 49)
  • Normalization to 3NF, and deliberate denormalization (Ch 51–52)
  • The star schema (Ch 53)
πŸ§ͺ Self-check questions
  1. What does an index cost you, and when is one not worth adding?
  2. WHERE YEAR(order_date) = 2026 is slow despite an index on order_date. Why, and what is the fix?
  3. A query was fast last week and is slow today. The SQL and the indexes are unchanged. What do you check first?
  4. Why is an index on (order_date, customer_id) useless for a query filtering only on customer_id?
  5. Is storing the price on the order line a normalization mistake?
  6. When is denormalization the right answer, and what do you owe the reader when you do it?
πŸ“ Sample answers
  1. Every index must be updated on every insert, update, and delete, and it consumes storage. So an index is a tax on writes paid to make reads faster. It is not worth it on a small table (scanning 18 rows beats traversing a tree), on a column that is rarely filtered, or when it duplicates the leading columns of an index you already have.

  2. The function wraps the column, so the engine cannot use the index β€” it would have to compute YEAR() for every row to find out which qualify. Rewrite as a half-open range: >= '2026-01-01' AND < '2027-01-01'. That keeps the column bare and SARGable. See Chapter 48.

  3. The execution plan, and specifically the gap between estimated and actual row counts. A large divergence points at stale statistics after a bulk load or delete, or at parameter sniffing β€” not at a missing index. Fixing the wrong thing here is how a day disappears.

  4. Because a composite index is sorted by its first column. Rows for a given customer_id are scattered throughout it, so there is nothing to seek to. Put the equality-filtered column first: (customer_id, order_date) serves both that filter and a date range within it.

  5. No β€” it is a different fact. The product’s price is what it costs today; the line’s price is what it cost at the moment of sale. Product prices change, and an order must not change retrospectively. Conflating them is the actual bug; separating them is correct design.

  6. When you have measured a read problem that no index or rewrite fixes. What you owe the reader is a written statement of how the copies are kept in step β€” trigger, job, or application β€” and a reconciliation query that detects divergence. Duplicated data drifts; finding out from a customer is the expensive way.

🎯 Give a simple example

Pick any slow query you have met. Describe the sequence you would follow β€” plan first, then what β€” and name one thing you would not do until you had evidence.


Part index Prerequisites Previous Next Full course