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 needsSUBSTRINGto 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_pricestays inorder_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_priceis 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:
- βοΈ Does any cell contain a list, or a comma?
- βοΈ Do I have columns like
x1,x2,x3? - βοΈ Is the same text repeated across many rows?
- βοΈ If I updated one fact, would I have to change more than one row?
- βοΈ Can I add a new βthingβ without inventing a fake related record?
- βοΈ If I deleted a row, would I lose an unrelated fact forever?
- βοΈ Does any non-key column depend on another non-key column?
- βοΈ 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
- Take the
orders_flattable above and normalize it to 3NF on paper, then in SQL. - Find the 3NF violation in this table and fix it:
employees(employee_id, name, department_id, department_name, department_budget). - Design a schema for a school: students, courses, enrolments, teachers, grades. Get it to 3NF.
- Explain in one sentence why
order_items.unit_priceis 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
customersand 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
UPDATEsomewhere 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
COUNTscans 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
- Add an
order_countcolumn tocustomers, populate it, and write the verification query. - Deliberately insert an order without updating the counter, then run your verification query and see it catch the drift.
- Build a
daily_sales_summarytable and a refresh script. - 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_itemscarriesquantity,unit_price, anddiscountβ 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_productwould join to a separatedim_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
- Draw the conceptual model for a library: members, books, copies, loans, reservations, fines.
- Turn it into a 3NF logical model, then a physical one with real
CREATE TABLEstatements. - Build a star schema for ShopDB sales and load it from the operational tables.
- Implement SCD Type 2 for
dim_customerand simulate a customer moving city. - 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
- What does an index cost you, and when is one not worth adding?
WHERE YEAR(order_date) = 2026is slow despite an index onorder_date. Why, and what is the fix?- A query was fast last week and is slow today. The SQL and the indexes are unchanged. What do you check first?
- Why is an index on
(order_date, customer_id)useless for a query filtering only oncustomer_id? - Is storing the price on the order line a normalization mistake?
- When is denormalization the right answer, and what do you owe the reader when you do it?
π Sample answers
-
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.
-
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. -
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.
-
Because a composite index is sorted by its first column. Rows for a given
customer_idare 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. -
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.
-
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 |