Video in progress
Explain the second and third normal forms (2NF, 3NF) with a simple example.
2NF: when the key is composite, every column must depend on the whole key, not just part of it. 3NF: a non-key column must not depend on another non-key column, that is, everything depends on "the key, the whole key and nothing but the key".
📖 Answer
A 2NF violation. order_items(order_id, product_id, quantity, product_name), with the key (order_id, product_id). product_name depends only on product_id, not on order_id. The result: the product name is repeated in every order, renaming it means updating thousands of rows, and if you miss one you end up with two different names.
The fix: move product_name into a products table.
A 3NF violation. employees(id, name, department_id, department_name). department_name depends on the department, not on the employee (id → department_id → department_name). When the department is renamed, you again have to update every employee row.
CREATE TABLE departments (id bigint PRIMARY KEY, name text NOT NULL);
CREATE TABLE employees (
id bigint PRIMARY KEY,
name text NOT NULL,
department_id bigint REFERENCES departments(id)
);
In practice one exception comes up a lot: storing a copy of the price (price) on the order line. That isn't denormalization gone wrong, it's actually correct: the product's price changes tomorrow, but the price on the order has to stay the value at the time of sale.
Sign up to mark studied questions and save your progress.