A Level Computer Science · Chapter 8 · Component 01: Computer systems
A relational database stores data in linked tables, so that each fact is kept once, can be changed in one place and can be found quickly.
This chapter teaches why flat files cause repetition and errors, and how entities, keys and relationships organise data into related tables. It then teaches normalisation to first, second and third normal form, and how indexes, integrity rules and data exchange keep a database fast and reliable.
In this chapter · jump to a section
Start here
Your route through this chapter
By the end of this chapter you will be able to:
- explain the problems of storing data in a flat file, including update, insertion and deletion anomalies
- identify primary, composite, foreign and secondary keys
- draw entity relationship diagrams, and resolve a many-to-many relationship with a link table
- put a table into first normal form by removing repeating groups
- identify partial and transitive dependencies, and normalise tables to second and third normal form
- explain how an index speeds up searching, and how referential integrity protects the data
- describe methods of capturing, selecting and exchanging data
Time: three sessions, about 4 hours, plus the programming task.
You need first: records and arrays from Arrays, records, stacks and queues, and binary search from Searching and sorting algorithms.
The big picture
The big picture
Almost every organisation keeps records. A school stores its pupils, their classes and their marks; a shop stores its customers, products and orders; a hospital stores its patients, appointments and treatments. These records are used every day, by many people, and they must stay accurate for years.
The simplest way to store records is a flat file: one big table, with a row for each record. But a flat file soon repeats itself. If every order row includes the customer's name and address, a customer with fifty orders has their address stored fifty times. Changing it means changing fifty rows, and missing one leaves the data contradicting itself.
A relational database splits the data into several tables, one for each kind of thing it stores, called an entity. Customers go in one table, orders in another and products in a third. The tables are linked by keys: each order row holds the number of its customer, rather than a copy of the customer's details. To show an order with its customer's name, the database looks up the customer number in the Customers table, a step called a join.
Normalisation is the process of designing those tables well. It follows a series of rules, called normal forms, that remove repeated data step by step. A database in third normal form stores each fact in exactly one place, so it can be changed in one place and can never contradict itself.
Designing a database well takes care, because a poor design is very hard to fix once the database is full of data and programs depend on it. A few hours spent drawing an entity relationship diagram and normalising the tables can save years of patching errors. That is why database design is a skill of its own.
Good design also makes a database fast. Indexes let it find a record among millions in a handful of reads, and integrity rules stop errors such as an order for a customer who does not exist. The SQL language, taught in the next chapter, then queries and changes the tables.
The software that looks after a database is called a database management system, or DBMS. It stores the tables on disk, finds and changes records on request, checks the rules the designer set, and lets many people use the data at once. Users and programs never touch the files directly: they ask the DBMS, which keeps the data consistent however many requests arrive.
Section 1
Flat files and relational databases
A flat file
A flat file stores all the data in a single table. Each row is a record and each column is a field. Flat files are simple to set up and easy to understand, which makes them fine for small lists, such as the names and phone numbers of a sports team.
Spreadsheets are often used as flat files. They are familiar and flexible, and anyone can add a column or sort the rows. But a spreadsheet has no idea what the data means. It will happily accept a customer number that does not exist, a date in the wrong format or two spellings of the same town. Nor can it stop two people overwriting each other's changes.
Redundancy and anomalies
When the same data is stored more than once, it is redundant. Redundancy wastes space, but its real danger is that the copies can disagree. Three kinds of problem, called anomalies, follow from it.
An update anomaly happens when a change must be made in many places. If Ann Lee moves to York, all three of her rows must be changed; if one is missed, the database says she lives in two towns at once. An insertion anomaly happens when data cannot be added without other, unrelated data. A new customer who has not yet ordered anything has no row to go in. A deletion anomaly happens when deleting one fact deletes another. If Zoe Kim's only order is cancelled and deleted, the shop loses her name and town as well.
These problems grow with the data. A small club's flat file of twenty members can be checked by eye, but a shop with thousands of customers cannot. Every extra copy of a fact is another chance for an error to creep in. Errors in a database are often found only when a customer complains or a report gives the wrong total.
Worked example 1: an update anomaly
Ann Lee, customer C1, moves from Leeds to York. How many rows of the flat file must change?
| Working | Reason |
|---|---|
| Find every row with CustomerID C1 | Her details are copied onto each of her orders |
| Orders 1001, 1003 and 1004 belong to C1 | Three rows hold her town |
| So 3 rows must be changed | Every copy must be updated |
| Miss one and the data contradicts itself | That is an update anomaly |
Relational databases
A relational database stores the data in several tables, called relations, linked together. Customers are stored once in a Customers table, and each order stores only the CustomerID of the customer who placed it. Ann's town is then stored once, and changing it changes it for all her orders at once.
Relational databases bring other benefits too, because they are run by a DBMS. The DBMS can give different users different permissions, so a sales assistant sees orders but not salaries. It can let many users work at the same time without overwriting each other's changes. It takes regular backups. It also keeps the way the data is stored separate from the programs that use it, so the storage can be improved without rewriting them.
Figure 8.1 shows the cost of a flat file as customers place more orders. Move the number of orders per customer and compare the cells stored and the rows to change. Then switch on the wrong model.
Redundancy in a flat file
- Cells, flat file
- 700
- Cells, two tables
- 480
- Rows to change, flat file
- 5
Common mistake: thinking a change to a flat file changes only one row. In a flat file, a customer's details are copied onto every one of their rows. Changing their address means changing every copy, and missing one leaves the data contradicting itself.
Worked example 2: counting cells
A shop has 100 customers, each with 5 orders. Each customer has 4 details and each order 3 details. Compare the cells stored in a flat file and in two linked tables.
| Working | Reason |
|---|---|
| Orders = 100 × 5 = 500 | Every customer has five orders |
| Flat: 500 × (4 + 3) = 3,500 cells | Every order row repeats the customer's details |
| Two tables: 100 × 4 + 500 × (3 + 1) = 2,400 cells | Each order stores one CustomerID instead |
| The two tables save 1,100 cells | The saving grows with more orders each |
Worked example 3: when there is no repetition
Now 50 customers each place only one order. Compare the cells again.
| Working | Reason |
|---|---|
| Flat: 50 × (4 + 3) = 350 cells | Each customer appears on one row only |
| Two tables: 50 × 4 + 50 × (3 + 1) = 400 cells | The CustomerID is stored twice for each customer |
| The two tables use 50 more cells | There was no repetition to remove |
| But they still allow customers with no orders | Normalisation is about integrity, not only space |
Derivation: when linked tables save space
Suppose c customers each have k orders, with a customer fields and b order fields. A flat file stores every customer field on every order row.
Linked tables store each customer once, and each order with its own fields plus one foreign key.
With c = 100, a = 4 and k = 5, the saving is 100 × (16 − 5) = 1,100 cells. With k = 1 it is −c, a small cost, because there was no repetition to remove.
Check yourself. In the flat file, the shop cancels and deletes order 1005. Which anomaly does this cause?
Show the answer
It causes a deletion anomaly. Order 1005 was Zoe Kim's only order, so deleting it also deletes the only record of her name and town.
Section 2
Entities, attributes and keys
Entities and attributes
An entity is a kind of thing about which data is stored, such as a customer, a product or an order. Each entity becomes a table. An attribute is a property of an entity, such as a customer's name or town, and becomes a field, or column, of the table. Each row holds one instance of the entity, such as one particular customer.
Every row of a table describes one instance in the same way, using the same fields. The order of the rows does not matter, and neither does the order of the columns: the database finds data by its values, not by its position. This is different from a spreadsheet, where a formula might depend on a value being in a particular cell.
A table is often written in a short form, with the table name followed by its attributes in brackets. The primary key is underlined, or written first and marked. For example, Customer(CustomerID, Name, Town) describes a table of customers.
Primary and composite keys
A primary key is a field, or set of fields, whose value is different for every record in the table. It identifies each record uniquely. A CustomerID such as C1 is a good primary key; a name is not, because two customers can share a name.
When no single field is unique, two or more fields can be combined into a composite key. In a table of order lines, one order can contain many products and one product can appear on many orders. But each order contains each product only once, so OrderID and ProductID together form a composite key.
Foreign and secondary keys
A foreign key is a field in one table that is the primary key of another table. It links the two. The CustomerID field in the Orders table is a foreign key: its value matches the CustomerID of a record in the Customers table.
Common mistake: thinking a foreign key must be unique in its own table. A foreign key is unique in the table it points to, where it is the primary key, but not in the table that holds it. Customer C1 appears once in Customers but on three rows of Orders.
A secondary key is a field that is not the primary key but is often used to search, such as a customer's surname or postcode. The database can build an index on a secondary key so that searches on it are fast, even though its values need not be unique.
Choosing a primary key
A primary key can be a natural key, a value that already exists in the real world, such as a car's registration number or a book's ISBN. Or it can be a surrogate key, a value made up by the database, such as a customer number that simply counts up from 1. Surrogate keys are common, because real-world values can change, repeat or be missing.
A good primary key must be unique, must never be empty, and should never change. If a customer's email address were the key, changing their email would mean changing every order that refers to it. A customer number that never changes avoids this, which is why most systems give every record a number of its own.
Worked example 4: naming the keys
The tables are Customer(CustomerID, Name, Town) and Order(OrderID, Date, CustomerID). Identify the primary and foreign keys, and a likely secondary key.
| Working | Reason |
|---|---|
| CustomerID is the primary key of Customer | It is different for every customer |
| OrderID is the primary key of Order | It is different for every order |
| CustomerID in Order is a foreign key | It matches the primary key of Customer |
| Name could be a secondary key | Staff often search by name, though names repeat |
Check yourself. Why is a pupil's date of birth a poor choice of primary key?
Show the answer
Two pupils can easily share a date of birth, so it would not identify each pupil uniquely. A primary key must be different for every record.
Section 3
Relationships and entity relationship diagrams
Kinds of relationship
Entities are linked by relationships, which have a degree. In a one-to-one relationship, each instance of one entity links to exactly one of the other, such as each pupil having one locker. In a one-to-many relationship, one instance links to many, such as one customer placing many orders. In a many-to-many relationship, many link to many, such as students and clubs: each student joins several clubs, and each club has many students.
An entity relationship diagram, or ERD, draws each entity as a box and each relationship as a line. A crow's foot, a three-pronged end, marks the many end of a relationship. A plain end marks the one end.
ERDs are drawn before any tables are built, because they show the overall shape of the data at a glance. A designer lists the entities, decides how each pair is related, and checks the diagram with the users. Questions such as "can an order have more than one customer?" are much cheaper to answer on a diagram than after the database is full of data.
To read a relationship, read it in both directions. Between Customer and Order: one customer places many orders, and each order is placed by one customer. If both directions say "many", the relationship is many-to-many and needs a link table.
Resolving many-to-many relationships
A relational database cannot store a many-to-many relationship directly. A Students table cannot hold a list of clubs in one field, and a Clubs table cannot hold a list of students. Instead, a link table is added between them, with one row for each pairing. The many-to-many relationship becomes two one-to-many relationships.
The link table, here Membership(StudentID, ClubID, JoinDate), has a composite key made of the two foreign keys. It can also hold attributes that belong to the pairing itself, such as the date the student joined that club.
Notice that JoinDate belongs in Membership and nowhere else. It is not a fact about the student, who joined several clubs on different dates. Nor is it a fact about the club, which many students joined at different times. It is a fact about one student in one club, so it lives in the row that represents that pairing.
Common mistake: thinking a many-to-many relationship can be stored without a link table. Storing a list of clubs in one field of the Students table breaks the rule that each field holds one value. A link table, with one row per student and club, is the only way to store the relationship properly.
Worked example 5: sizing a link table
A sixth form has 30 students, and each belongs to exactly 2 clubs. How many rows does the Membership table hold?
| Working | Reason |
|---|---|
| Each membership is one student in one club | The link table has a row per pairing |
| Rows = 30 × 2 = 60 | Every student contributes two pairings |
| Each row holds a StudentID and a ClubID | The two foreign keys form the composite key |
| No list is stored in any single field | Each field still holds one value |
Worked example 6: a library
A library lends books to members. A member can borrow many books over time, and a book can be borrowed by many members. Design the tables.
| Working | Reason |
|---|---|
| Entities: Member and Book | These are the things the library stores |
| Member to Book is many to many | Each borrows many; each is borrowed many times |
| Add a link table Loan(MemberID, BookID, DateOut) | Resolve the many-to-many relationship |
| Member 1:M Loan and Book 1:M Loan | Two one-to-many relationships replace it |
In practice the same member may borrow the same book twice. So a Loan table usually has its own LoanID as its primary key, with MemberID and BookID as foreign keys. Choosing keys always depends on what the data really allows.
A hospital gives another example. A patient can have many appointments, and each appointment is with one doctor, while each doctor sees many patients. The entities are Patient, Doctor and Appointment. Appointment holds a PatientID and a DoctorID as foreign keys, so the many-to-many link between patients and doctors runs through the appointments.
Check yourself. Each pupil has one school email address, and each address belongs to one pupil. What degree is this relationship?
Show the answer
It is one-to-one, because each pupil links to exactly one address and each address links to exactly one pupil.
Section 4
First normal form
Repeating groups
A table that has not been normalised is in unnormalised form, often written UNF. It may contain repeating groups: sets of fields that occur several times for one record. An order record that lists every product on the order, each with its name and price, has a repeating group of products.
The rules of first normal form
A table is in first normal form, 1NF, when it has a primary key, every field holds a single, atomic value, and there are no repeating groups. Atomic means the value cannot sensibly be split further. A field holding "P1 Pen 1.20, P2 Pad 2.50" is not atomic, because it holds several products at once.
To reach 1NF, the repeating group is removed by giving each repeat its own row, and a key is chosen that identifies each row. Each order line becomes a row, and OrderID with ProductID becomes the composite key.
Atomic values matter because the database works field by field. A query can easily find every order containing a pen if each pen is in a field of its own. If the products are stored as a list in one field, the query must search inside text, which is slow and easily fooled. Lists also make it impossible to sort, total or count the items properly.
Deciding what is atomic needs judgement. A full name could be split into first name and surname if the users need to sort by surname. A date is normally treated as one value, even though it has a day, a month and a year. The test is whether the users ever need to work with the parts separately.
Common mistake: thinking a field holding a list of values is atomic. A field such as "Pen, Pad, Ink" looks like one value but holds three. It cannot be searched, sorted or counted properly, so it breaks first normal form.
Worked example 7: reaching first normal form
Order 2001 contains three products and order 2002 one product. Order 2003 contains two products. Convert the orders to first normal form.
| Working | Reason |
|---|---|
| Give each product on each order its own row | Removes the repeating group |
| Rows = 3 + 1 + 2 = 6 | One row per order line |
| Key = OrderID and ProductID together | Neither alone is unique on every row |
| The table is now in 1NF | Atomic values, no repeats, a primary key |
Check yourself. A pupils table has a field Subjects holding "Maths, Physics, Computing". Is it in 1NF? Why?
Show the answer
No. The Subjects field holds three values at once, so it is not atomic. Each pupil and subject pairing should be a row of its own, in a separate table.
Section 5
Second and third normal form
Dependencies
A field depends on another if knowing the second always tells you the first. A product's name depends on its ProductID: P2 is always the Pad. This is written ProductID → ProductName, and is called a functional dependency.
Dependencies come from the meaning of the data, not from the rows that happen to be in the table today. Suppose every customer so far lives in a different town. The town might then seem to decide the customer, but that is a coincidence: two customers could live in the same town tomorrow. So finding dependencies means asking the users how the data really behaves.
Second normal form
A table is in second normal form, 2NF, when it is in 1NF and has no partial dependencies. A partial dependency is one where a non-key field depends on only part of a composite key. In the 1NF order lines table, ProductName and Price depend on ProductID alone, and the customer's details depend on OrderID alone. Only the quantity, if stored, depends on both.
To reach 2NF, each partial dependency is moved into a table of its own, keyed by the part of the key it depends on. The order lines table splits into Orders(OrderID, CustomerID, Name), Products(ProductID, ProductName, Price) and OrderLines(OrderID, ProductID, Quantity).
Common mistake: thinking a table with a one-field key can have a partial dependency. A partial dependency needs a composite key, so that a field can depend on part of it. A table in 1NF whose primary key is a single field is automatically in 2NF.
Third normal form
A table is in third normal form, 3NF, when it is in 2NF and has no transitive dependencies. A transitive dependency is one where a non-key field depends on another non-key field, rather than directly on the key. In Orders(OrderID, Date, CustomerID, Name, Town), Name and Town depend on CustomerID, which in turn depends on OrderID.
To reach 3NF, the transitively dependent fields move to a table keyed by the field they depend on. The customer's details move to Customers(CustomerID, Name, Town), and Orders keeps only CustomerID as a foreign key. A short way to remember 3NF is that every non-key field depends on the key, the whole key, and nothing but the key.
Each part of that phrase matches one normal form. "The key" means every table has a primary key, as 1NF requires. "The whole key" means no field depends on only part of a composite key, which is 2NF. "Nothing but the key" means no field depends on another non-key field, which is 3NF.
Worked example 8: partial dependencies
The 1NF table has the key OrderID and ProductID. OrderID decides OrderDate, CustomerID, CustomerName and CustomerTown. ProductID decides ProductName and Price. The whole key decides Quantity. What normal form is it in, and how is it fixed?
| Working | Reason |
|---|---|
| OrderID alone decides the order and customer fields | A dependency on part of the key |
| ProductID alone decides ProductName and Price | This is another partial dependency |
| So the table is in 1NF but not 2NF | 2NF allows no partial dependencies |
| Split into Orders, Products and OrderLines | Each table keyed by what its fields depend on |
Worked example 9: a transitive dependency
The Orders table is now Orders(OrderID, OrderDate, CustomerID, CustomerName, CustomerTown). What normal form is it in, and how is it fixed?
| Working | Reason |
|---|---|
| Its key is the single field OrderID | So it has no partial dependencies |
| CustomerID decides CustomerName and CustomerTown | A non-key field depends on another non-key field |
| So the table is in 2NF but not 3NF | That is a transitive dependency |
| Split into Customers and Orders(OrderID, OrderDate, CustomerID) | The final tables are all in 3NF |
Worked example 10: a pupils table
Pupil(PupilID, Name, Form, Tutor) stores each pupil's form and the form's tutor. Every form has one tutor. Normalise it.
| Working | Reason |
|---|---|
| The key is PupilID, a single field | So the table is already in 2NF |
| Form decides Tutor | Every pupil in 12A has the same tutor |
| That is a transitive dependency, so not 3NF | Tutor depends on a non-key field |
| Split into Pupil(PupilID, Name, Form) and Form(Form, Tutor) | Each tutor is now stored once |
Normalised tables are not free. A query that needs data from several tables must join them, which takes extra work. Some systems that mainly read data, such as reporting databases, deliberately keep a little redundancy for speed. But for data that is changed often, third normal form is the safe default.
The whole process
Normalisation is easiest when it follows the same steps every time. Start from the unnormalised data and choose a key. Remove repeating groups to reach 1NF. Look for fields that depend on only part of a composite key and move them out to reach 2NF. Then look for fields that depend on other non-key fields and move them out to reach 3NF.
After each split, check that every new table has a primary key, and that the original data can be rebuilt by joining the tables on their keys. If a split loses data or makes it impossible to rebuild, it was wrong. The final design for the shop has four tables: Customer, Order, OrderLine and Product.
Check yourself. A table Membership(StudentID, ClubID, StudentName, JoinDate) has the key StudentID and ClubID. Which field breaks 2NF?
Show the answer
StudentName depends only on StudentID, which is part of the key, so it is a partial dependency. JoinDate depends on both fields, so it can stay.
Section 6
Indexes, integrity and exchanging data
Indexes
Finding a record by scanning the table may mean reading every record. An index is a separate, sorted list of the values of one field, each with a pointer to its record. Because the index is sorted, it can be searched by binary search, which halves the records left with every read. The index is much smaller than the table, because it holds only one field and a pointer for each record, so it can often be kept in memory.
Figure 8.2 compares the worst-case reads with and without an index as the table grows. Move the number of records and compare the bars. Then switch on the wrong model.
Searching with an index
- Reads without an index
- 1,000
- Reads with an index
- 10
Common mistake: thinking a database must read every record to find one. With an index on the key, the database uses binary search on the sorted index. A million records need about 20 reads, not a million, which is why indexed lookups stay fast as tables grow.
Derivation: reads needed with an index
Binary search on a sorted index of n keys looks at the middle key and discards half. After r reads, at most n ÷ 2^r keys are left.
So the worst case needs the smallest whole number of reads above log₂ n.
For n = 1,000,000, log₂ n is about 19.9, so 20 reads are enough. Doubling the table adds only one read.
Worked example 11: a million records
A table holds 1,000,000 customers. Compare the worst-case reads to find one by its key with and without an index.
| Working | Reason |
|---|---|
| Without an index: up to 1,000,000 reads | A scan may have to check every record |
| log₂ 1,000,000 ≈ 19.9 | Binary search halves the keys each read |
| With an index: 20 reads | The smallest whole number above 19.9 |
| The index makes the search 50,000 times faster | Divide the scan reads by the index reads |
Indexes have a cost. Every index takes storage space, and every time a record is added, changed or deleted, each index on the table must be updated too. So indexes are built on the fields that are searched often, such as primary keys and common secondary keys, not on every field.
An index can be built on any field, not only the primary key. A shop might index customers by postcode, so that delivery staff can list everyone on a route quickly. Real databases usually store an index as a balanced tree rather than a simple sorted list. Each node of the tree holds many keys, so the tree is very shallow and a lookup touches only a few disk blocks. The idea is the same as binary search: each step rules out most of the remaining keys.
Worked example 12: a smaller table
A table of 50,000 records has an index on its key. How many reads does a lookup need, and how many more if the table doubles?
| Working | Reason |
|---|---|
| log₂ 50,000 ≈ 15.6 | The table holds 50,000 keys |
| Reads = 15 + 1 = 16 | Round the logarithm down and add one |
| At 100,000 records, reads = 17 | Doubling adds only one read |
| The index stays fast as the table grows | The reads grow with log₂ n |
Referential integrity
Referential integrity means that every foreign key must match a primary key that really exists. An order cannot belong to customer C9 if there is no customer C9. The database enforces this. It refuses to add an order for a customer who does not exist, and it refuses, or handles carefully, the deletion of a customer who still has orders.
Referential integrity also covers changes to keys. If a customer's number had to change, every order holding the old number would have to change too, or the orders would be left pointing at nothing. This is another reason to choose primary keys that never change. Two common choices are offered when a linked record is deleted. A restricted delete refuses to delete a customer who has orders. A cascading delete removes the customer's orders as well. The right choice depends on what the organisation needs to keep.
Integrity rules are part of the database's design, not of the programs that use it. That matters because many programs may use the same database: a website, a phone app and a staff system might all add orders. If the rule lives in the database, every one of them is held to it, and no program can slip an invalid order past.
Capturing, selecting and exchanging data
Data must first be captured, or entered, into the database. It may be typed in through forms, read from paper by optical mark or character recognition, scanned from barcodes or QR codes, or collected automatically by sensors. Validation checks that each value is sensible, such as a date that exists or a mark between 0 and 100. Verification checks that it was copied correctly, such as by entering a password twice.
Common validation checks include a presence check, that a value has been entered at all, and a type check, that it is a number or a date as expected. A range check confirms a value lies between limits, and a format check that it matches a pattern such as a postcode. A length check confirms it has the right number of characters. A check digit, calculated from the other digits of a code, catches most mistakes in typing a barcode or account number.
Selecting data means retrieving only the records and fields that are needed, usually with a query language such as SQL. Exchanging data means moving it between systems. Common formats include CSV, where each record is a line of comma-separated values, and JSON and XML, which label every value with its field name. Electronic data interchange lets organisations, such as a shop and its supplier, send orders and invoices directly between their systems.
When data is exchanged, both sides must agree on its format and meaning. A date written 03/04 means 3 April in Britain but 4 March in the United States, so a shared format, such as year, month and day, avoids mistakes. Formats such as JSON and XML carry the field names with the data, so the receiver can check that each value is what it claims to be.
Check yourself. A user tries to delete a customer who still has three orders, and the database refuses. Which rule is it enforcing?
Show the answer
It is enforcing referential integrity, with a restricted delete. Deleting the customer would leave three orders whose foreign key pointed to a customer who no longer exists.
Reference
Key algorithms and definitions
| Term or algorithm | What it means | Example | Cost or rule to learn |
|---|---|---|---|
| Flat file | One table holding everything | Orders with customer details | Redundancy and anomalies |
| Anomalies | Update, insertion and deletion problems | Changing three copies of a town | Caused by redundancy |
| Primary key | Field unique for every record | CustomerID | Identifies each row |
| Composite key | Two or more fields that are unique together | OrderID with ProductID | Needed for link tables |
| Foreign key | Primary key of another table | CustomerID in Orders | Repeats in its own table |
| Many-to-many | Many instances link to many | Students and clubs | Resolve with a link table |
| 1NF | Atomic values, no repeating groups, a key | One row per order line | Remove lists from fields |
| 2NF | 1NF with no partial dependencies | Products split out | Only matters with a composite key |
| 3NF | 2NF with no transitive dependencies | Customers split out | The key, the whole key, nothing but the key |
| Index | Sorted keys with pointers | Index on CustomerID | ⌊log₂ n⌋ + 1 reads |
Programming task
Programming task: a normal form checker
Aim
Write a Python program that takes a table's primary key and its functional dependencies, and reports the highest normal form the table reaches, from 1NF to 3NF. It must name the dependency that stops it reaching the next form.
Design
The key is a set of field names, and each dependency is a pair: the set of fields on the left, and the set of fields they decide. A dependency is partial if its left side is part of the key, but not all of it, and it decides a non-key field. A dependency is transitive if its left side is not the whole key and contains a non-key field, and it decides a non-key field.
The checker assumes the table is already in 1NF, because repeating groups are easy to spot by eye. It looks for partial dependencies first, then transitive ones, and reports the first problem it finds.
Code
def normal_form(key, dependencies):
key = set(key)
for lhs, rhs in dependencies:
lhs, rhs = set(lhs), set(rhs)
if lhs < key and rhs - key:
return 1, f"partial: {sorted(lhs)} -> {sorted(rhs - key)}"
for lhs, rhs in dependencies:
lhs, rhs = set(lhs), set(rhs)
if not key <= lhs and lhs - key and rhs - key:
return 2, f"transitive: {sorted(lhs)} -> {sorted(rhs - key)}"
return 3, "no partial or transitive dependencies"
order_lines = (["OrderID", "ProductID"], [
(["OrderID"], ["OrderDate", "CustomerID", "CustomerName", "CustomerTown"]),
(["ProductID"], ["ProductName", "Price"]),
(["OrderID", "ProductID"], ["Quantity"]),
])
print(normal_form(*order_lines))
Python's set operators do most of the work. The test lhs < key is true when the left side is a proper part of the key. The expression rhs − key gives the fields decided that are not part of the key.
Testing
| Test | Input | Expected output | Why this test |
|---|---|---|---|
| 1 | The 1NF order lines | 1, partial on OrderID | Matches worked example 8 |
| 2 | Orders with CustomerID → name and town | 2, transitive on CustomerID | Matches worked example 9 |
| 3 | Customers(CustomerID, Name, Town) | 3 | A table already in 3NF |
| 4 | OrderLines(OrderID, ProductID, Quantity) | 3 | The whole key decides Quantity |
| 5 | Pupil with Form → Tutor | 2, transitive on Form | Matches worked example 10 |
| 6 | Membership with StudentID → StudentName | 1, partial on StudentID | Matches the check yourself question |
| 7 | A table with a single-field key and no other dependencies | 3 | A single key cannot give a partial dependency |
Evaluation
The checker reports the right normal form for every test, and names the dependency at fault, which tells the designer exactly which table to split. Test 7 confirms that a single-field key cannot cause a partial dependency.
The program trusts the dependencies it is given. In a real design, finding the dependencies is the hard part, and it needs knowledge of what the data means. An improvement would suggest the tables to split into, by moving each faulty dependency's fields into a new table keyed by its left side.
Practice
Practice ladder
Rung 1: Recall and fluency
Q1. Define the term foreign key.
Worked solution to Q1
A foreign key is a field in one table that is the primary key of another table. It links the two tables, so each record can refer to a record in the other table.
Q2. State the three conditions for a table to be in first normal form.
Worked solution to Q2
The table must have a primary key, every field must hold a single atomic value, and there must be no repeating groups of fields. Each record then fits on one row.
Q3. Describe an insertion anomaly, with an example.
Worked solution to Q3
An insertion anomaly happens when data cannot be added without other, unrelated data. In a flat file of orders, a new customer who has not yet ordered anything has no row, so their details cannot be stored.
Rung 2: Application
Q4. A shop has 200 customers with 3 orders each. Customers have 5 details and orders 4. Find the cells stored flat and in two linked tables.
Worked solution to Q4
There are 200 × 3 = 600 orders. The flat file stores 600 × (5 + 4) = 5,400 cells. The two tables store 200 × 5 + 600 × (4 + 1) = 4,000 cells, a saving of 1,400.
Q5. In the flat file of orders, how many rows must change if customer C1 changes her name?
Worked solution to Q5
Customer C1 placed orders 1001, 1003 and 1004, and her name is copied onto each. So 3 rows must change, and missing any of them would cause an update anomaly.
Q6. A school has 120 pupils, each taking 4 subjects. How many rows does the link table between pupils and subjects hold?
Worked solution to Q6
Each pupil and subject pairing is one row of the link table. So the table holds 120 × 4 = 480 rows, with PupilID and SubjectID together as the composite key.
Q7. How many reads does an indexed lookup need in a table of 1,000 records?
Worked solution to Q7
Binary search on the index needs ⌊log₂ 1000⌋ + 1 reads. Since log₂ 1000 is about 9.97, that is 9 + 1 = 10 reads, compared with up to 1,000 without an index.
Rung 3: Analysis
Q8. Book(ISBN, Title, PublisherID, PublisherName) has the key ISBN, and PublisherID decides PublisherName. Normalise it to 3NF.
Worked solution to Q8
The key is one field, so the table is in 2NF. But PublisherName depends on PublisherID, a non-key field, which is a transitive dependency. Split it into Book(ISBN, Title, PublisherID) and Publisher(PublisherID, PublisherName).
Q9. Explain why OrderLines(OrderID, ProductID, Quantity) is in third normal form.
Worked solution to Q9
Its only non-key field, Quantity, depends on the whole composite key, since the same product can be ordered in different amounts on different orders. So there are no partial or transitive dependencies.
Q10. Explain why a single table cannot store which students belong to which clubs.
Worked solution to Q10
Each student joins many clubs and each club has many students. Storing a list of clubs in one field breaks first normal form, so a link table with one row per student and club is needed.
Q11. Fifty customers each place exactly one order. Explain why linked tables use more cells than a flat file here, and why they may still be better.
Worked solution to Q11
With no repetition to remove, the linked tables only add a foreign key on each order, so they use 50 more cells. But they still let a customer be stored before their first order and survive the deletion of their only order.
Rung 4: Stretch
Q12. Use the derivation to find the smallest number of orders per customer k for which linked tables save space when a = 4.
Worked solution to Q12
Linked tables save space when a(k − 1) > k. With a = 4 that is 4k − 4 > k, so 3k > 4 and k > 1.33. So from 2 orders per customer onwards, the linked tables are smaller.
Q13. A table of 1,000,000 records doubles in size every year. How many reads does an indexed lookup need after three years?
Worked solution to Q13
After three years the table holds 8,000,000 records. Since log₂ 8,000,000 is about 22.9, a lookup needs 22 + 1 = 23 reads, only three more than today's 20.
Q14. Explain why a cascading delete may be dangerous for an online shop's customer records.
Worked solution to Q14
Deleting a customer would silently delete all their past orders too. The shop may need those orders for its accounts, tax records or refunds, so a restricted delete, or marking the customer as inactive, is often safer.
Exam practice
Exam technique and worked answer workshop
When asked to normalise, work one normal form at a time and say which rule each step fixes. Name each dependency you remove, such as "CustomerName depends on CustomerID, a non-key field, so this is a transitive dependency".
Write tables in the short form, with the primary key underlined or marked and foreign keys identified. Check every final table: each non-key field should depend on the key, the whole key and nothing but the key.
In ERDs, mark the many end with a crow's foot, and resolve every many-to-many relationship with a link table before writing the tables.
Exam question 1 (4 marks · Paper 01 · about 5 minutes)
A shop stores all its orders in a flat file, with the customer's name and address on every order.
(a) Explain what is meant by an update anomaly, using this example. [2]
(b) Explain how a relational database avoids it. [2]
Mark scheme for exam question 1
- B1 the customer's address is stored on every one of their orders
- B1 changing it means changing every row, and missing one leaves the data inconsistent
- B1 customers are stored once in their own table
- B1 orders hold the CustomerID as a foreign key, so the address is changed in one place
Exam question 2 (5 marks · Paper 01 · about 7 minutes)
A shop has 100 customers with 5 orders each. Each customer has 4 details and each order 3 details.
(a) Calculate the cells stored in a flat file. [2]
(b) Calculate the cells stored in a customer table and an order table linked by a foreign key. [2]
(c) State the saving. [1]
Mark scheme for exam question 2
- M1 500 orders × 7 fields
- A1 3,500 cells
- M1 100 × 4 + 500 × 4
- A1 2,400 cells
- B1 1,100 cells
Exam question 3 (4 marks · Paper 01 · about 5 minutes)
Students can join many clubs, and each club has many students.
(a) State the degree of the relationship between Student and Club. [1]
(b) Explain how it should be stored in a relational database. [2]
(c) State the primary key of the new table. [1]
Mark scheme for exam question 3
- B1 many-to-many
- B1 a link table, such as Membership, is added between them
- B1 with one row for each student and club, giving two one-to-many relationships
- B1 StudentID and ClubID together, a composite key
Exam question 4 (6 marks · Paper 01 · about 9 minutes)
A table in first normal form is OrderLine(OrderID, ProductID, OrderDate, CustomerID, CustomerName, ProductName, Price, Quantity), with the key OrderID and ProductID.
(a) Identify a partial dependency, and explain why it stops the table being in 2NF. [2]
(b) Normalise the data to third normal form, giving each table with its key. [4]
Mark scheme for exam question 4
- B1 ProductName and Price depend only on ProductID, or the order details only on OrderID
- B1 they depend on part of the composite key, which 2NF does not allow
- B1 Product(ProductID, ProductName, Price)
- B1 OrderLine(OrderID, ProductID, Quantity)
- B1 Order(OrderID, OrderDate, CustomerID)
- B1 Customer(CustomerID, CustomerName), removing the transitive dependency
Exam question 5 (6 marks · Paper 01 · about 9 minutes)
A school keeps all its data on pupils, classes and teachers in one large spreadsheet. Discuss the benefits and drawbacks of moving it to a normalised relational database.
Mark scheme for exam question 5
Level 3 (5–6 marks): a balanced discussion of the benefits and drawbacks, linked to the school's data, covering redundancy, anomalies, integrity and the cost of joins and set-up. The answer reaches a justified conclusion. It is well organised and uses technical terms accurately.
Level 2 (3–4 marks): correct benefits and at least one drawback, with some link to the school. The conclusion is limited.
Level 1 (1–2 marks): some relevant points, such as that data is not repeated, with little application. The answer may lack structure.
0 marks: no response or no response worthy of credit.
Indicative content:
- the spreadsheet repeats teacher and class details on many pupil rows
- a change, such as a teacher's room, must be made on many rows, risking update anomalies
- a new class with no pupils yet cannot be stored, an insertion anomaly
- normalised tables store each fact once, so it is changed in one place
- referential integrity stops pupils being placed in classes that do not exist
- indexes make finding a pupil fast even with many records
- drawbacks: designing the tables and moving the data takes time and skill
- queries need joins across tables, which are slower and harder for staff to write
- conclusion: for data used and changed for years, a normalised database is worth the cost
Annotated model answer: exam question 5
"In the spreadsheet, a teacher's name and room are copied onto every pupil they teach. Changing a room means editing many rows, and missing one leaves the data contradicting itself." (Redundancy and the update anomaly, linked to the school.)
"A new class cannot be added until a pupil joins it, which is an insertion anomaly. Normalised tables store each pupil, class and teacher once, so each fact is changed in one place. Referential integrity stops a pupil being put in a class that does not exist." (Insertion anomaly, the benefit and integrity.)
"Against this, designing the tables and moving the data takes time and skill. Staff must also learn queries that join tables, which are harder than reading a spreadsheet." (Two drawbacks.)
"The school's data will be used and changed for many years. So the accuracy gained is worth the set-up cost, and it should move to a normalised database." (A justified conclusion.)
This answer reaches Level 3 and scores 6 marks. It weighs benefits against drawbacks and ties every point to the school's data.
Exam question 6 (4 marks · Paper 01 · about 5 minutes)
Pupil(PupilID, Name, Form, Tutor) records each pupil's form and the form's tutor.
(a) Explain why the table is in second normal form. [1]
(b) Explain why it is not in third normal form, and normalise it. [3]
Mark scheme for exam question 6
- B1 its primary key is a single field, so there can be no partial dependency
- B1 Tutor depends on Form, a non-key field
- B1 so there is a transitive dependency
- B1 Pupil(PupilID, Name, Form) and Form(Form, Tutor)
Exam question 7 (5 marks · Paper 01 · about 7 minutes)
A table holds 1,000,000 customer records.
(a) State the worst-case number of reads to find one customer without an index. [1]
(b) Calculate the worst-case reads with an index on the key. [2]
(c) Give one disadvantage of adding an index. [1]
(d) Explain what is meant by referential integrity. [1]
Mark scheme for exam question 7
- B1 1,000,000 reads
- M1 ⌊log₂ 1,000,000⌋ + 1
- A1 20 reads
- B1 it takes extra space, and must be updated whenever records are added, changed or deleted
- B1 every foreign key value must match an existing primary key in the linked table
Exam question 8 (6 marks · Paper 02 · about 9 minutes)
Order records are stored in arrays orderID and customerID, with n records. Write a function countOrders(customerID, n, target) that returns how many orders belong to the customer target. State what it returns for C1 in the orders table of this chapter.
Mark scheme for exam question 8
- B1 a function header with the three parameters
- B1 a count starting at 0
- B1 a loop over all n records
- B1 each customerID compared with target
- M1 the count increased when they match
- A1 the count returned, which is 3 for C1
Annotated model answer: exam question 8
function countOrders(customerID, n, target)
count = 0
for i = 0 to n - 1
if customerID[i] == target then
count = count + 1
endif
next i
return count
endfunction
The header earns the first mark and the count starting at 0 the second. The loop and the comparison earn the next two marks. Increasing the count on a match earns the method mark, and returning it, 3 for customer C1, earns the last.
Connections
Synoptic link
Indexes rely on binary search from Searching and sorting algorithms. Many databases store their indexes as balanced trees, close relatives of the binary search trees in Linked lists, hash tables, graphs and trees. Hash tables are also used to index records by key.
The tables designed here are queried and changed with SQL in SQL and transaction processing. Data protection law, which limits what personal data may be stored and for how long, is covered in Legal, moral, ethical and cultural issues.
Synoptic question 1. An index on a table of 500,000 records is searched by binary search. How many reads does a lookup need in the worst case?
Answer to synoptic question 1
Since log₂ 500,000 is about 18.9, the worst case is 18 + 1 = 19 reads. Without the index, a scan could need all 500,000.
Recap
Recap and next step
- Flat files repeat data, causing update, insertion and deletion anomalies; relational databases store each entity in its own linked table.
- A primary key is unique for every record; a composite key combines fields; a foreign key is another table's primary key and may repeat.
- Relationships are one-to-one, one-to-many or many-to-many; a many-to-many relationship needs a link table.
- First normal form has a key, atomic values and no repeating groups.
- Second normal form has no partial dependencies; third normal form has no transitive dependencies.
- An index needs ⌊log₂ n⌋ + 1 reads; referential integrity keeps every foreign key valid; data is captured, validated, selected and exchanged in standard formats.
Next chapter: SQL and transaction processing shows how to query, join and change these tables with SQL. It also shows how a database keeps data safe when many users change it at once.
For your exam board
OCR A Level Computer Science (H446): this chapter covers section 1.3.2, Databases, in Component 01: flat files and relational databases, keys, entity relationship modelling, normalisation to 3NF, indexing, referential integrity, and methods of capturing, selecting, managing and exchanging data.
AQA A Level Computer Science (7517): relational databases, entity relationship modelling, keys and normalisation to third normal form appear in the fundamentals of databases section, assessed on Paper 2.