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.
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.