Relational databases and normalisation
A-Level Computer Science · Databases and Data Security
Why not a single flat file
A flat file repeats the same data on every row. That wastes space, but the real cost is update anomalies: change a customer's address and you must find every row containing it, and any row you miss now holds a contradiction. A relational database stores each fact once.
The vocabulary
An entity becomes a table; an attribute becomes a field; a record is one row. A primary key uniquely identifies a record. A foreign key is a primary key of another table used to link them. A composite key uses two or more fields together, which is what a link table needs. Referential integrity means a foreign key must match an existing primary key — the database refuses to create an orphan record.
Normalisation
1NF: no repeating groups; every field holds a single atomic value. 2NF: in 1NF, and every non-key field depends on the whole primary key — this only bites when the key is composite. 3NF: in 2NF, and no non-key field depends on another non-key field (no transitive dependency).
Many-to-many
A relational database cannot store a many-to-many relationship directly. It is resolved by a link table whose primary key is the composite of the two foreign keys — students and courses become students, courses and enrolments.
What normalisation costs
Fewer anomalies and less redundancy, but more tables, so queries need more joins and can run more slowly. That trade-off is the evaluation point: a data warehouse used only for reading is often deliberately denormalised.
Worked example: normalizing a table to 3NF
A single table stores orders:
ma_don, ngay, ma_kh, ten_kh, dia_chi_kh, ma_sp, ten_sp, don_gia, so_luong
One order may contain several products. Normalize to 3NF.
Solution
Step 1: to 1NF. Because one order has several products, the product fields form a repeating group. Split the rows so that each row is one product in one order. The primary key must then be the composite key (ma_don, ma_sp).
Step 2: to 2NF: remove dependence on PART of the key.
• ngay, ma_kh, ten_kh, dia_chi_kh depend only on ma_don, not on ma_sp ⇒ split them into the table DON_HANG.
• ten_sp, don_gia depend only on ma_sp ⇒ split them into the table SAN_PHAM.
• so_luong depends on both ⇒ it stays in the link table.
Step 3: to 3NF: remove transitive dependencies. In the table DON_HANG, ten_kh and dia_chi_kh depend on ma_kh, and ma_kh in turn depends on ma_don; that is a transitive dependency. Split them into the table KHACH_HANG.
Result: four tables:
KHACH_HANG(ma_kh, ten_kh, dia_chi_kh)
SAN_PHAM(ma_sp, ten_sp, don_gia)
DON_HANG(ma_don, ngay, ma_kh*)
CHI_TIET_DON(ma_don*, ma_sp*, so_luong)
(underline $=$ primary key, the $*$ sign $=$ foreign key)
Concrete benefit. When a customer moves house, you edit exactly ONE row in KHACH_HANG instead of hunting for every order row of theirs, and because the edit is made in one place, no inconsistency can arise.