Relational Databases, Normalisation and Transactions

IB Computer Science · Option: Object-Oriented Programming and Databases

Structure. A relational database stores data in tables; each row is a record describing one instance, and each column is a field. A primary key is the field or combination of fields that uniquely identifies each record. A foreign key is a field holding the primary key of another table, and it is what creates relationships. Referential integrity is the rule that a foreign key must refer to a record that actually exists, which prevents orphaned data such as an enrolment pointing to a deleted course.

Why normalise. Normalisation exists to remove the three anomalies caused by storing the same fact in more than one place. The update anomaly: changing a teacher's name requires editing many rows, and missing one leaves the database contradicting itself. The insertion anomaly: a new course cannot be recorded until a student enrols on it, because the row would have no key. The deletion anomaly: removing the last enrolment on a course destroys the record of the course itself. Learn the anomalies, not just the definitions of the normal forms — examiners ask for the anomalies.

The normal forms. First normal form requires atomic values with no repeating groups: a field must not hold a list. Second normal form additionally requires every non-key field to depend on the whole primary key, which matters only when the key is composite. Third normal form additionally removes transitive dependencies, where a non-key field depends on another non-key field rather than on the key. The working rule is that every field must depend on the key, the whole key, and nothing but the key.

The cost. Normalisation is not free. Data spread across several tables must be recombined with joins, so read-heavy systems perform more work per query. Some systems therefore deliberately keep controlled redundancy, trading consistency for speed; a data warehouse used for analysis is usually organised very differently from the transactional database it draws from. An index makes searching a column much faster but slows insertion and consumes storage, which is the same trade-off in miniature.

Transactions. A transaction is a group of operations that must all succeed or all fail — transferring money requires both the debit and the credit. Databases guarantee atomicity (all or nothing), consistency (rules such as referential integrity always hold), isolation (concurrent transactions do not see each other's partial work) and durability (a committed result survives a crash). Isolation is what prevents two simultaneous bookings of the same seat.

FROM A TABLE WITH REPEATED DATA TO THIRD NORMAL FORM BEFORE — a single table MaSV TenSV MaMon TenMon TenGV S01 An M01 Toán Ms. Lan S01 An M02 Lý Mr. Hai S02 Binh M01 Toán Ms. Lan S03 Chi M01 Toán Ms. Lan Red text = data that is REPEATED AFTER — four tables in 3rd normal form SinhVien MaSV (khoá chính) TenSV GiangVien MaGV (khoá chính) TenGV MonHoc MaMon (khoá chính) TenMon TeacherID (foreign key) DangKy StudentID (foreign key) CourseID (foreign key) the two columns above = primary key Each piece of data is stored EXACTLY ONCE, in exactly one table THE THREE ANOMALIES CAUSED BY REPEATED DATA 1. UPDATE ANOMALY: if Ms. Lan changes her name it must be edited in many rows; miss one row and the data contradicts itself 2. INSERT ANOMALY: cannot store a new course until some student registers — because StudentID is missing as part of the key 3. DELETE ANOMALY: deleting the last student of the Physics course also loses the Physics course and its teacher
Normalization is not a formal ritual — it exists to eliminate exactly the three anomalies listed in the yellow strip, and exams always ask about those three anomalies rather than asking for definitions of the normal forms. The root cause of all three is repeated data. In the table on the left, the name of the Math course and the name of Ms. Lan appear three times only because three students are registered for that course. The red text marks every repeated cell. Each copy is a chance for the data to become contradictory. The update anomaly happens because one fact is stored in many places: changing Ms. Lan's name requires editing every row, and missing just one row makes the database contradict itself with no way of knowing which copy is right. The insert anomaly happens because two independent facts are tied to the same row: a new course cannot be recorded when no student has registered, because that row lacks the student ID which is part of the key. The delete anomaly is the flip side of the same problem: deleting the last registration record of the Physics course will also delete the information about the Physics course and the teacher who teaches it, even though we only wanted to delete one registration. The fix is to split BY PRINCIPLE. Each table describes exactly one kind of entity; every column in the table must depend on the whole primary key and only on the primary key. In the original table, TeacherName does not depend directly on the key but on CourseID, and CourseID in turn depends on the key — that is a transitive dependency, and removing it is precisely the step that brings the table to third normal form. The result and the cost. After splitting, each piece of data is stored exactly once in exactly one table, foreign keys link them together, and referential integrity guarantees there is no registration pointing to a course that does not exist. The cost that must be stated in an evaluation: every query now needs a JOIN of several tables, so a read-heavy system may deliberately keep some repeated data to trade consistency for speed.

Worked example: Normalizing a table and pointing out the three anomalies

A single table stores: OrderID, OrderDate, CustomerID, CustomerName, CustomerAddress, ProductID, ProductName, UnitPrice, Quantity. One order can contain several products. Point out the three anomalies, then split the table to third normal form and explain each step.

Solution

The three anomalies. On update: when a customer moves, CustomerAddress must be edited in every row of every order of that customer; missing one row leaves the system with two contradictory addresses for the same person and no way to know which is right. On insert: a new product cannot be recorded in the catalog until someone orders it, because that row would lack OrderID and CustomerID. On delete: deleting the last order containing a product will also delete the name and unit price of that product from the system.

Step 1 — first normal form. The table is in first normal form if each cell holds only a single value. If initially several products of one order were stored in the same cell, they must first be split into several rows. The primary key at this point is the composite OrderID plus ProductID, because both are needed to identify a row uniquely.

Step 2 — second normal form: remove dependencies on PART of the key. Examine each non-key field. OrderDate, CustomerID, CustomerName and CustomerAddress depend only on OrderID, that is, only on part of the composite key. ProductName and UnitPrice depend only on ProductID, also only part. Only Quantity truly depends on both. So split into three tables: Orders with OrderID as primary key, OrderDate, CustomerID, CustomerName, CustomerAddress; Products with ProductID as primary key, ProductName, UnitPrice; and OrderDetails with OrderID and ProductID as the composite primary key together with Quantity.

Step 3 — third normal form: remove transitive dependencies. In the Orders table, CustomerName and CustomerAddress do not depend on OrderID directly — they depend on CustomerID, and CustomerID in turn depends on OrderID. This is exactly a transitive dependency, and it is the reason the update anomaly still exists after step 2. Split further into: Orders with OrderID as primary key, OrderDate, CustomerID as a foreign key; and Customers with CustomerID as primary key, CustomerName, CustomerAddress.

The final result — four tables. Customers, Orders, Products, OrderDetails. Check the three anomalies again: changing a customer's address now edits exactly one row in the Customers table; adding a new product only needs one row added to Products without any order; and deleting an order does not touch the Products table. All three anomalies have disappeared.

The cost that must be stated to earn evaluation marks. A report listing customer names together with product names now has to join four tables instead of reading a single table, so each query costs more work. For a system with very many reads and very few writes — for example a data warehouse serving analytics — the redundancy may be deliberately kept to trade consistency for speed. But for a transactional database, where data changes constantly, normalization is almost always the right choice.

Worked example: Why transactions and isolation are needed

A flight booking system records a seat with two operations: decrease the number of free seats by one, and create a booking record. Explain what happens if the system loses power between the two operations, and what happens if two people book the last seat at exactly the same moment.

Solution

Scenario 1 — power failure between two operations. If the number of free seats has dropped but the booking record has not been created, the system permanently loses a seat: it cannot be sold to anyone because the counter says it is gone, yet it belongs to no one because there is no record. This is an inconsistent state, and the danger is that it does not reveal itself — there is no error message, just a seat that has vanished.

The fix: atomicity. The two operations must be wrapped in one transaction. The database writes the changes to a log before applying them, and only when both operations have finished does it commit the transaction. If the power fails before the commit, then on restart the system rolls back the half-finished work, returning the data to exactly the state it was in before the transaction began. The principle is all or nothing, with no state in between.

Scenario 2 — two people book the last seat at the same time. Without any protection, the sequence of events could go like this: transaction A reads that 1 seat is left; transaction B also reads that 1 seat is left because A has not finished writing; A writes the remaining seats as 0 and creates a booking record; B also writes the remaining seats as 0 and creates a booking record. The result is that two people are confirmed for one seat, and the counter drops only by one even though the seat was sold twice.

The fix: isolation. Isolation guarantees that transactions running concurrently produce results as if they had run one after another. The common mechanism is the lock: transaction A locks the free-seats record until it has finished committing, so B has to wait; when B is allowed to continue, it reads that the free seats are 0 and is rejected. An alternative mechanism is optimistic concurrency control: both run, but at commit time the system checks whether the value has changed since it was read, and if so it aborts that transaction and asks it to retry.

The other two properties, stated briefly to complete the set. Consistency guarantees that every constraint, such as referential integrity, still holds before and after the transaction. Durability guarantees that once a transaction has been committed and the user has received a success message, the result is not lost even if the server shuts down suddenly right afterward — this is achieved by writing the log to persistent storage before reporting success.

The cost to mention when evaluating. Locks reduce concurrency: while A holds the lock, B has to wait, so throughput falls when many transactions touch the same record. For this reason large systems often allow a lower isolation level in places where some risk is acceptable, trading absolute correctness for speed.

Common mistake

Trap 1 — memorizing the definitions of the normal forms without being able to state the THREE ANOMALIES. Exam questions ask what problem normalization removes: update, insertion and deletion anomalies. That is the answer that earns marks.
Trap 2 — presenting normalization as something that is always right. The cost is that every query has to join several tables; a system that does a great deal of reading may deliberately keep redundancy. Stating this trade-off is how you earn evaluation marks.
Trap 3 — describing transactions using atomicity alone. Atomicity handles failure midway, but it is ISOLATION that stops two people booking the same seat. These are two different problems and need two different properties.

Key takeaway

Lesson 2 summary. Four things to take into the exam room. One, the three anomalies — update, insertion, deletion — and the root cause of all three is duplicated data. Two, the practical rule: every field must depend on the key, the whole key, and nothing but the key; transitive dependency is what third normal form removes. Three, the cost of normalization is the join, so always state the trade-off when evaluating. Four, the four properties of a transaction, and remember that atomicity handles failure midway while isolation handles concurrent access.

← Object-Oriented Programming · All IB Computer Science lessons · Practice IB Computer Science questions (free, instant scoring) · Classes in Detail: Constructors, Static Members, UML and Program Structure →