Normalisation vs denormalisation: explain 1NF, 2NF, 3NF and when to break the rules.
Normalisation organises tables to remove redundancy so each fact is stored once, which prevents update anomalies (changing a customer's address in one row but not another).
Normal forms
- 1NF: atomic values, no repeating groups (no
phone1, phone2, phone3columns or comma-separated lists); each row is unique. - 2NF: 1NF, and every non-key column depends on the whole primary key (matters for composite keys).
order_items(order_id, product_id, product_name)violates it, sinceproduct_namedepends only onproduct_id. - 3NF: 2NF, and no non-key column depends on another non-key column (no transitive dependencies).
employees(id, dept_id, dept_name)violates it. - BCNF: a stricter 3NF where every determinant is a candidate key.
"The key, the whole key and nothing but the key."
Denormalisation
Deliberately duplicating data to make reads faster: storing customer_name on orders for an invoice history, keeping a comment_count on posts, or building reporting tables and materialised views. Accept it when reads vastly outnumber writes or joins are too expensive, and keep the copies in sync with transactions, triggers, events or scheduled refreshes.
OLTP systems are usually normalised to 3NF; analytics warehouses use star schemas (a fact table with denormalised dimension tables).
Example
-- Normalised (3NF)
CREATE TABLE customers (id BIGINT PRIMARY KEY, name VARCHAR(100) NOT NULL, email VARCHAR(255) UNIQUE NOT NULL);
CREATE TABLE products (id BIGINT PRIMARY KEY, name VARCHAR(200) NOT NULL, price NUMERIC(10,2) NOT NULL);
CREATE TABLE orders (id BIGINT PRIMARY KEY, customer_id BIGINT NOT NULL REFERENCES customers(id), created_at TIMESTAMP NOT NULL);
CREATE TABLE order_items (
order_id BIGINT REFERENCES orders(id),
product_id BIGINT REFERENCES products(id),
qty INT NOT NULL CHECK (qty > 0),
unit_price NUMERIC(10,2) NOT NULL, -- deliberate copy: the price at the time of purchase
PRIMARY KEY (order_id, product_id)
);unit_price looks like duplication of products.price, but it is a different fact (the historical price), so it is correct to store it.
Follow-up questions interviewers ask
Try answering each one before you open it.
What is a materialised view?
A query result stored as a table and refreshed on demand or on a schedule (REFRESH MATERIALIZED VIEW in PostgreSQL, refresh options in Oracle). It gives denormalised read speed for dashboards while the source tables stay normalised. MySQL has no native materialised views; use summary tables updated by events or jobs.