A Level Computer Science · Chapter 9 · Component 01: Computer systems
SQL asks a relational database questions and changes its data, while transaction processing keeps that data correct when many people use it at once.
This chapter teaches how to select, filter, sort, join and summarise data with SQL, and how to define tables and insert, update and delete records. It then teaches transactions and the ACID properties, and how record locking, serialisation and timestamps stop simultaneous users from corrupting each other's work.
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:
- write SELECT queries with WHERE, AND, OR, NOT, LIKE, BETWEEN and ORDER BY
- join two tables with INNER JOIN, and explain what happens without a join condition
- summarise data with COUNT, SUM, AVG, MAX, MIN and GROUP BY
- define tables with CREATE TABLE, and change data with INSERT, UPDATE and DELETE
- explain the four ACID properties of a transaction, and commit and rollback
- explain how simultaneous transactions can lose updates, and how record locking, serialisation and timestamp ordering prevent it
Time: three sessions, about 4 hours, plus the programming task.
You need first: tables, keys and normalisation from Databases and normalisation.
The big picture
The big picture
A normalised database spreads its data across several tables, each storing one kind of thing. That keeps the data accurate. But it means the answer to an everyday question, such as which pupils scored over 50 and who their tutors are, is spread across tables. Something must gather the pieces together.
SQL, the Structured Query Language, is that something. It is the standard language for relational databases, used by almost every database system in the world. An SQL query says what data is wanted, and the database management system works out how to find it. SQL is declarative: it describes the result, not the steps.
SQL is everywhere, even where people never see it. A shopping site listing a category, a school system printing a class list and a phone app showing recent messages all do the same thing. An SQL query is usually running behind the scenes. Learning SQL means learning to read and write those questions directly.
SQL does more than ask questions. It also creates tables, adds new records, changes existing ones and deletes them. These commands change the stored data, so they must be used with care: a missing condition can change every record in a table at once.
SQL has two main parts. The data manipulation language, or DML, reads and changes the data: SELECT, INSERT, UPDATE and DELETE. The data definition language, or DDL, creates and changes the structure of the database: CREATE TABLE, ALTER TABLE and DROP TABLE. Most of a database user's work is DML, while DDL is mainly used when the database is first designed.
When many people use a database at the same moment, a new danger appears. Two cashiers might update the same bank account at the same instant, and one of their changes could vanish. Transaction processing groups each set of changes into a single unit that either happens completely or not at all. It also controls how simultaneous units interact, so the data stays correct however busy the system gets.
Section 1
Selecting data with SQL
SELECT, FROM and WHERE
A query starts with SELECT, followed by the fields wanted, then FROM and the table they come from. An asterisk, *, means every field. A WHERE clause keeps only the records that meet a condition, and ORDER BY sorts the result, in ascending order unless DESC is added.
SELECT Name, Score
FROM Pupils
WHERE Score >= 50
ORDER BY Score DESC
The database reads the table, keeps the rows where the condition is true, keeps only the fields named after SELECT, and sorts the result. SQL keywords are usually written in capitals to make them stand out, but the database does not care about their case.
The database does not necessarily read the rows in the order they were stored, and without ORDER BY it may return them in any order. So whenever the order matters, a query should say so. ORDER BY can sort on several fields, such as ORDER BY Form, Score DESC, which groups the pupils by form and puts the highest score first within each form.
A field can be renamed in the result with AS. SELECT Name AS Pupil gives the column the heading Pupil. This is especially useful for calculated values, such as SELECT Name, Score * 2 AS Doubled, which also shows that SELECT can calculate new values from the stored fields.
Worked example 1: a simple query
Find the names and scores of pupils with at least 50, highest first.
| Working | Reason |
|---|---|
| FROM Pupils, WHERE Score >= 50 | Only rows meeting the condition are kept |
| Ava 72, Cara 88 and Dev 51 pass | Ben, 45, and Eli, 39, fail |
| SELECT Name, Score keeps two fields | The other fields are left out |
| ORDER BY Score DESC gives Cara, Ava, Dev | DESC sorts from highest to lowest |
Combining conditions
Conditions can be combined with AND, OR and NOT. AND needs both conditions to be true, OR needs at least one, and NOT reverses a condition. Brackets make the order of a long condition clear, just as in arithmetic. The comparison operators are =, <> for not equal, <, >, <= and >=. Text values are written in single quotation marks, such as '12A'.
Comparisons work on text as well as numbers. Name < 'C' is true for Ava and Ben, because text is compared in alphabetical order, character by character. Dates compare in time order. Care is needed with text and numbers mixed together: as text, '9' comes after '10', because the first characters are compared first.
Common mistake: confusing AND with OR. AND keeps only the rows that meet both conditions, so it usually returns fewer rows. OR keeps rows that meet either condition, so it usually returns more. "Pupils in 12A who scored over 50" needs AND.
Worked example 2: AND against OR
Compare WHERE Form = '12A' AND Score > 50 with WHERE Form = '12A' OR Score > 50.
| Working | Reason |
|---|---|
| AND: Ava and Cara | Both are in 12A and scored over 50 |
| Eli is in 12A but scored 39, so AND rejects him | Both conditions must be true |
| OR: Ava, Cara, Dev and Eli | Each meets at least one condition |
| Dev is in 12B but scored 51, so OR keeps him | One true condition is enough |
LIKE and BETWEEN
LIKE matches text against a pattern. The symbol % stands for any number of characters, and _ for exactly one. So Name LIKE 'C%' matches every name starting with C, and Name LIKE '%a' every name ending in a. BETWEEN tests a range, including both ends: Score BETWEEN 40 AND 60 is the same as Score >= 40 AND Score <= 60.
The IN operator tests whether a value is one of a list. WHERE Form IN ('12A', '12C') is shorter than writing Form = '12A' OR Form = '12C'. A missing value is stored as NULL, which is not the same as zero or an empty string. It is tested with IS NULL, because NULL is not equal to anything, not even another NULL.
Worked example 3: patterns and ranges
Find the pupils whose name starts with C or whose score is between 40 and 50.
| Working | Reason |
|---|---|
| Name LIKE 'C%' matches Cara | % stands for the rest of the name |
| Score BETWEEN 40 AND 50 matches Ben, 45 | Both ends of the range are included |
| OR combines them: Ben and Cara | A row needs only one of the two |
| The rows come out in table order | No ORDER BY clause was given |
Queries are read by the database, not run line by line, so the order of the clauses is fixed: SELECT, FROM, WHERE, then ORDER BY. A query can also remove repeated rows with SELECT DISTINCT, so that a list of forms shows each form once however many pupils it has.
Writing a query is a matter of answering three questions in turn. Which table or tables hold the data? Which rows are wanted? Which fields should be shown, and in what order? The first answer gives FROM, the second WHERE and the third SELECT and ORDER BY. Working in this order makes even long queries manageable.
Check yourself. Which pupils does WHERE NOT Form = '12A' return?
Show the answer
It returns Ben and Dev, the two pupils in 12B. NOT reverses the condition, so every pupil who is not in 12A is kept.
Section 2
Joining tables
Why joins are needed
Normalisation stores each fact once, which is good for accuracy but means most useful questions need data from more than one table. The Pupils table holds each pupil's form, and a separate Forms table holds each form's tutor. To list pupils with their tutors, the database must match each pupil row with the right Forms row. This is called a join.
INNER JOIN
An INNER JOIN combines rows from two tables where a condition, given after ON, is true. The condition almost always matches a foreign key with the primary key it refers to. Field names that appear in both tables are written with the table name in front, such as Pupils.Form, so the database knows which one is meant.
Some versions of SQL also allow a join to be written in the WHERE clause. Both tables are listed after FROM, and a condition such as WHERE Pupils.Form = Forms.Form matches them. The result is the same. The INNER JOIN form is clearer, because it keeps the join condition separate from the conditions that filter the rows.
SELECT Name, Tutor
FROM Pupils INNER JOIN Forms ON Pupils.Form = Forms.Form
WHERE Score > 50
Figure 9.1 joins the two tables and filters the result. Move the minimum score and watch the rows change. Then switch on the wrong model.
Joining two tables
- Rows returned
- 3
- Pupils kept by WHERE
- 3
Common mistake: forgetting the join condition. Without ON Pupils.Form = Forms.Form, the database pairs every pupil with every form. Each pupil then appears with both tutors, and the result has the two table sizes multiplied together, most of it nonsense.
A join can be thought of as a lookup. For each pupil row, the database looks up the pupil's form in the Forms table and copies the tutor's name alongside. With an index on the Forms table's primary key, each lookup takes only a few reads, so even very large joins are fast.
Worked example 4: a join
List the names and tutors of pupils who scored over 50.
| Working | Reason |
|---|---|
| Join each pupil to the Forms row with the same Form | ON Pupils.Form = Forms.Form matches them |
| Ava and Cara match 12A, Ms Khan; Dev matches 12B, Mr Lee | Each pupil gets their own form's tutor |
| WHERE Score > 50 keeps Ava, Cara and Dev | Ben and Eli scored too little |
| Result: Ava Ms Khan, Cara Ms Khan, Dev Mr Lee | Three rows, one per pupil kept |
Worked example 5: no join condition
How many rows does a join of Pupils and Forms give with no ON condition at all?
| Working | Reason |
|---|---|
| Every pupil row is paired with every form row | Nothing restricts the pairs |
| Rows = 5 × 2 = 10 | Five pupils times two forms |
| Each pupil appears twice, once with each tutor | Half of the rows are wrong |
| The correct join gives 5 rows, one per pupil | Each pupil belongs to one form |
Derivation: how many rows a join returns
With no condition, every row of table A is paired with every row of table B. This is called the Cartesian product.
Now add a condition matching a foreign key in A to the primary key of B. Each row of A matches exactly one row of B, because the primary key is unique.
For 5 pupils and 2 forms, the product has 10 rows but the proper join only 5. With real tables of thousands of rows, a missing condition can produce millions of rows.
Worked example 6: joining and filtering on the other table
List the pupils whose tutor is Mr Lee.
| Working | Reason |
|---|---|
| Join Pupils to Forms on Form | Tutor is only stored in Forms |
| WHERE Tutor = 'Mr Lee' | The condition uses a field from the joined table |
| Ben and Dev are in 12B, whose tutor is Mr Lee | They are the only pupils in 12B |
| Result: Ben Mr Lee, Dev Mr Lee | Two rows, one for each pupil |
Joins can chain across more than two tables. A shop might join Customers to Orders on CustomerID, then Orders to OrderLines on OrderID, then OrderLines to Products on ProductID, to list every product each customer has bought. Each join follows one foreign key to the primary key it refers to.
An inner join only keeps rows that have a match in both tables. A pupil whose form was missing from Forms would vanish from the result. Other kinds of join exist for this case: a left join keeps every row of the first table, filling the missing fields with NULL. Inner joins are by far the most common, because a well-designed database with referential integrity rarely has unmatched rows.
The order in which a database carries out a query is not the order in which it is written. It starts with FROM and any joins, then applies WHERE, then groups and aggregates, and only then picks the fields after SELECT and sorts the result. Thinking in this order explains many puzzles, such as why WHERE cannot use a group's count.
Check yourself. A query joins 40 orders to 25 customers but forgets the ON condition. How many rows does it return?
Show the answer
It returns the Cartesian product: 40 × 25 = 1,000 rows. With the condition, each order matches one customer, giving 40 rows.
Section 3
Summarising data
Aggregate functions
Aggregate functions combine many rows into a single value. They answer questions about the data as a whole, rather than about any single record, such as how many pupils there are or what their average mark is. COUNT counts rows, SUM adds up the values in a field, AVG finds their mean, and MAX and MIN find the largest and smallest. COUNT(*) counts every row, while COUNT of a field counts only the rows where that field has a value.
SELECT COUNT(*) FROM Pupils WHERE Score >= 50
This query returns a single number: 3, the number of pupils with at least 50. The WHERE clause is applied first, so only those rows are counted.
Common mistake: thinking COUNT adds up the values. COUNT counts how many rows there are; it does not add up what is in them. SELECT COUNT(Score) FROM Pupils gives 5, the number of scores, while SUM(Score) gives their total, 295.
GROUP BY
GROUP BY splits the rows into groups that share a value, and applies the aggregate function to each group separately. The result has one row per group. A field listed after SELECT must either be in the GROUP BY clause or inside an aggregate function, because each group produces only one row.
Worked example 7: counting per group
How many pupils are in each form?
| Working | Reason |
|---|---|
| SELECT Form, COUNT(*) FROM Pupils GROUP BY Form | One result row per form |
| 12A: Ava, Cara and Eli | Three rows share the value 12A |
| 12B: Ben and Dev | Two rows share the value 12B |
| Result: 12A 3, 12B 2 | COUNT runs once for each group |
Worked example 8: averages and extremes
Find the average score in each form, and the highest and lowest scores overall.
| Working | Reason |
|---|---|
| 12A: (72 + 88 + 39) ÷ 3 = 66.33 | AVG within the 12A group |
| 12B: (45 + 51) ÷ 2 = 48 | AVG within the 12B group |
| MAX(Score) = 88 and MIN(Score) = 39 | No GROUP BY, so one row for the whole table |
| Cara has the top score and Eli the lowest | 88 and 39 belong to them |
Worked example 9: totals with a condition
Find the total score of the pupils in 12B.
| Working | Reason |
|---|---|
| WHERE Form = '12B' keeps Ben and Dev | The condition is applied before summing |
| SUM(Score) = 45 + 51 = 96 | Add the scores of the rows kept |
| The result is a single value, 96 | One aggregate, no grouping |
| COUNT(*) for the same rows would give 2 | COUNT counts rows instead of adding values |
Aggregates combine with joins. Joining Pupils to Forms and grouping by Tutor counts each tutor's pupils: Ms Khan has 3 and Mr Lee has 2. The join brings in the tutor's name, and the grouping then works on it like any other field.
A condition on a group, such as "forms with more than two pupils", cannot go in WHERE, because WHERE tests one row at a time before grouping. SQL uses a separate HAVING clause for that, placed after GROUP BY. For example, GROUP BY Form HAVING COUNT(*) > 2 would return only 12A.
Aggregates ignore NULL values. If one pupil had no score yet, AVG(Score) would average only the scores that exist, and COUNT(Score) would count only those, while COUNT() would still count every pupil. So COUNT() and COUNT(Score) can give different answers, and the difference shows how many values are missing.
Aggregates are what turn stored records into information. A head of year does not want to read every mark. They want the average for each form, the number of pupils below a target, and the highest score in the year. Each of these is one short query with an aggregate, often combined with WHERE and GROUP BY.
GROUP BY can use more than one field. Grouping by Form and then by a Gender field, say, would give one row for each combination that occurs. Each extra field splits the groups more finely, and the aggregate is worked out separately for every small group.
Check yourself. What does SELECT AVG(Score) FROM Pupils return?
Show the answer
It returns 59. The five scores add up to 295, and 295 ÷ 5 = 59.
Section 4
Defining and changing data
Creating tables
The data definition part of SQL creates and changes the structure of tables. CREATE TABLE names the table and lists its fields, each with a data type, and states the primary key and any foreign keys. Common data types include INTEGER, REAL for decimals, VARCHAR(n) for text of up to n characters, DATE and BOOLEAN.
CREATE TABLE Pupils (
PupilID INTEGER PRIMARY KEY,
Name VARCHAR(30) NOT NULL,
Form VARCHAR(3),
Score INTEGER,
FOREIGN KEY (Form) REFERENCES Forms(Form)
)
NOT NULL means the field must always have a value. The FOREIGN KEY line tells the database to enforce referential integrity: it will refuse a pupil whose form does not exist in Forms. ALTER TABLE adds, removes or changes fields in an existing table, and DROP TABLE deletes a table entirely.
Choosing data types carefully protects the data. A score stored as INTEGER cannot accidentally hold the word "absent", and a DATE field rejects 31 February. The database checks every value as it is stored, so many mistakes are caught at once rather than discovered later in a report.
Constraints add further rules. UNIQUE stops two records sharing a value, such as an email address, and CHECK tests a condition, such as Score >= 0. Because the rules are part of the table's definition, every program that uses the database is held to them.
DROP TABLE and DELETE are different. DELETE FROM Pupils removes the rows but keeps the empty table, ready for new data. DROP TABLE Pupils removes the table itself, its structure and every row, so anything that refers to it must be changed. Both are permanent once the transaction is committed, so they are used with great care.
Inserting, updating and deleting
INSERT INTO adds a new record, listing its values in the order of the fields. UPDATE changes existing records: SET gives the new values, and WHERE chooses which records to change. DELETE FROM removes the records that meet a WHERE condition.
INSERT INTO Pupils VALUES (6, 'Fay', '12B', 60)
UPDATE Pupils SET Score = Score + 5 WHERE Form = '12B'
DELETE FROM Pupils WHERE Score < 40
Common mistake: forgetting the WHERE clause in UPDATE or DELETE. Without WHERE, UPDATE changes every record in the table and DELETE removes every record. UPDATE Pupils SET Score = 0 sets all five scores to zero, not one.
Worked example 10: an update
Every pupil in 12B is given 5 bonus marks. Write the command and give the new scores.
| Working | Reason |
|---|---|
| UPDATE Pupils SET Score = Score + 5 WHERE Form = '12B' | SET can use the old value |
| Ben: 45 + 5 = 50 | Ben is in 12B |
| Dev: 51 + 5 = 56 | Dev is in 12B |
| Ava, Cara and Eli are unchanged | The WHERE clause skips 12A |
Worked example 11: a delete and an insert
Delete every pupil with a score below 40, then add Fay, pupil 6, in 12B with 60. How many rows does the table end with?
| Working | Reason |
|---|---|
| DELETE FROM Pupils WHERE Score < 40 removes Eli | Only Eli scored below 40 |
| Four rows remain | Ava, Ben, Cara and Dev |
| INSERT INTO Pupils VALUES (6, 'Fay', '12B', 60) | The values follow the field order |
| The table ends with 5 rows | One removed, one added |
Because commands like these change real data, careful users first run a SELECT with the same WHERE clause to see which rows would be affected. If the SELECT returns the expected rows, the UPDATE or DELETE with that condition will change exactly those rows and no others.
Programs that build SQL commands from what users type must take care. If a program simply pastes a user's text into a query, a cleverly written input could change the meaning of the command. Well-written programs pass user input to the database separately from the command itself, using parameterised queries. The input is then always treated as data, never as part of the SQL.
Check yourself. What does UPDATE Pupils SET Score = 0 do to the table?
Show the answer
With no WHERE clause, it sets the score of every pupil to 0. All five rows are changed, which is almost never what was intended.
Section 5
Transactions and ACID
What a transaction is
A transaction is a group of database operations that must be treated as a single unit. Moving £50 from account A to account B is one transaction made of two updates: subtract £50 from A, and add £50 to B. If the system crashed between the two, the money would vanish from A without ever reaching B.
Transactions are ended in one of two ways. COMMIT makes all the changes permanent. ROLLBACK undoes every change made since the transaction began, returning the database to the state it was in before. If anything goes wrong part-way through, the database rolls the transaction back automatically.
Transactions matter wherever several changes belong together. Booking a seat means taking a payment and marking the seat as sold. Placing an order means creating an order record, adding its order lines and reducing the stock of each product. In each case, a half-finished set of changes would leave the data wrong.
In SQL, a transaction is usually marked with BEGIN TRANSACTION at the start and COMMIT at the end. Every command between them belongs to the transaction. If any command fails, or the program issues ROLLBACK, none of the changes take effect. Many databases also treat each single command as a small transaction of its own.
A rollback can also be chosen by the program, not only forced by a failure. A booking program might start a transaction, mark a seat as sold, and then find that the customer's payment has been declined. It issues ROLLBACK, and the seat is free again, exactly as if nothing had happened.
The ACID properties
Reliable transaction processing guarantees four properties, remembered as ACID. Atomicity means a transaction happens completely or not at all; it is never left half done. Consistency means a transaction takes the database from one valid state to another, so every rule, such as referential integrity, still holds afterwards.
Isolation means simultaneous transactions do not interfere: the result is the same as if they had run one after another. Durability means that once a transaction is committed, its changes survive even a power cut or crash, because they have been written to permanent storage.
Common mistake: thinking a transaction can be left partly done. Atomicity forbids it. If the second update of a transfer fails, the first is rolled back too. The database never shows money taken from one account but not added to the other.
Worked example 12: a failed transfer
A transfer of £50 moves money from A, holding £200, to B, holding £80. The system crashes after the first update. What do the accounts hold, with and without atomicity?
| Working | Reason |
|---|---|
| Without atomicity: A = 200 − 50 = £150, B = £80 | The second update never happened |
| Total = 150 + 80 = £230, so £50 has vanished | Before the transfer the total was £280 |
| With atomicity: the first update is rolled back | The transaction did not commit |
| A = £200 and B = £80, total £280 | The database is consistent again |
Consider a cash machine. Withdrawing money is one transaction: check the balance, reduce it, and release the notes. If the machine jams before the notes come out, the transaction is rolled back and the balance restored. The customer is never charged for cash they did not receive. Durability is usually provided by a transaction log. Before changing the data, the database writes a record of the change to a log on permanent storage. After a crash, it reads the log: committed transactions are redone, and uncommitted ones are undone, so the data ends in a correct state.
Consistency is shared between the database and the programmer. The database enforces the rules it knows, such as primary keys, foreign keys and CHECK constraints. The programmer must make sure each transaction does the right thing, such as subtracting from one account exactly what is added to the other. Together these keep every committed state valid.
Full isolation can be slow, because transactions may have to wait for one another. So databases offer different isolation levels. The strictest makes every set of transactions behave exactly as if run one at a time. Weaker levels allow some interference, such as an inconsistent read, in return for speed. Banks and booking systems choose the strict levels, where correctness matters most.
Check yourself. Which ACID property means a committed booking is not lost in a power cut?
Show the answer
Durability. Once the booking is committed, it has been written to permanent storage, so it survives the power cut.
Section 6
Concurrent access
The lost update
A busy database runs many transactions at the same time. Problems arise when two of them use the same record. Suppose an account holds £100, transaction T1 adds £50 and transaction T2 adds £20. Each reads the balance, adds its amount and writes the result back.
If T1 and T2 both read the balance before either writes, both read £100. T1 writes £150, then T2 writes £120 over it. The account ends with £120 instead of £170, and T1's deposit has been lost. This is called a lost update.
Other problems come from the same cause. A dirty read happens when one transaction reads a change that another has made but not yet committed. If the second then rolls back, the first has used a value that never really existed. An inconsistent read happens when a transaction reads several records while another is half way through changing them, and so sees a mixture of old and new values.
Record locking
Record locking stops this. Before a transaction changes a record, it locks it. Any other transaction that wants the same record must wait until the lock is released, when the first transaction commits. T2 then reads the balance that T1 wrote, and both updates survive.
Locks can cover different amounts of data. Locking a whole table is simple but makes every other user wait, even for unrelated records. Locking a single record lets other users work on the rest of the table, so far more transactions can run at once. Most databases lock records, and lock larger amounts only when a transaction changes a large part of a table.
Some locks are shared and some are exclusive. Many transactions can hold a shared lock to read the same record at once, because reading changes nothing. A transaction that wants to write needs an exclusive lock, which no one else can hold at the same time.
Locking is called a pessimistic approach: it assumes conflicts will happen and prevents them in advance. Timestamp ordering is more optimistic: it lets transactions run freely and only rolls one back if a conflict actually happens. When conflicts are rare, optimistic methods waste less time waiting; when they are common, the cost of restarting many transactions makes locking better.
Figure 9.2 runs the two transactions with and without locking. Change the amount T1 adds and compare the final balance. Then switch on the wrong model.
Two transactions on one record
- Final balance
- £120
- Correct total
- £170
- Money lost
- £50
Common mistake: thinking two transactions on the same record cannot interfere. Each transaction reads, changes and writes in separate steps. If two interleave, the second write can replace the first, so a deposit is lost unless the database controls access to the record.
Worked example 13: without locking
An account holds £500. T1 adds £200 and T2 adds £100 at the same time, without locking. What is the final balance?
| Working | Reason |
|---|---|
| T1 reads £500; T2 reads £500 | Both read before either writes |
| T1 writes 500 + 200 = £700 | T1's update is stored |
| T2 writes 500 + 100 = £600 | T2 overwrites T1's result |
| Final balance £600; £200 has been lost | The correct total is £800 |
Worked example 14: with locking
Run the same two transactions with record locking.
| Working | Reason |
|---|---|
| T1 locks the record and reads £500 | No one else can use it now |
| T2 must wait for the lock | The record is locked by T1 |
| T1 writes £700 and unlocks; T2 then reads £700 | T2 sees T1's result |
| T2 writes 700 + 100 = £800 | Both updates are kept |
Derivation: the money lost by an interleaved update
Let the starting balance be b, with T1 adding a₁ and T2 adding a₂. If both read b before either writes, the last write wins.
If T2 waits for T1, it reads b + a₁ and adds to that.
So the whole of T1's change is lost: £50 when the balance is £100, and £200 when it is £500, as in worked example 13.
Deadlock
Locking brings a new danger. Suppose T1 locks account A and then wants account B, while T2 has locked B and wants A. Each waits for the other to release its lock, so neither can ever continue. This is deadlock. It is like two cars meeting on a narrow bridge, each waiting for the other to reverse. The database detects it, rolls one transaction back to free its locks, and restarts it later.
Deadlocks can also be made less likely. If every transaction always locks records in the same order, such as by account number, two transactions can never each hold the record the other wants. Many systems also set a time limit: a transaction that has waited too long for a lock is assumed to be deadlocked and is rolled back.
Serialisation and timestamps
Serialisation means arranging simultaneous transactions so the result is the same as running them one at a time, in some order. Locking is one way to achieve it. Another is timestamp ordering. Each transaction is given a timestamp when it starts, and each record remembers the timestamps of the last transactions to read and write it. A transaction may try to change a record that a later transaction has already read or written. It is then rolled back and restarted, so transactions always take effect in timestamp order.
Commitment ordering is a further method. Transactions are allowed to run at the same time, but are committed in an order that keeps the result serialisable. The order takes account of which transactions depend on the data of others. It avoids some of the waiting that locks cause.
Redundancy
Large databases also keep copies of their data on more than one disk or server, so that a single failure does not lose data or stop the service. This deliberate redundancy is different from the repeated data that normalisation removes: it is a planned, managed copy of the whole database, kept in step automatically.
If the main server fails, a copy on another server takes over, often within seconds, so users barely notice. Copies kept in another building or city also protect against fire or flood. Keeping the copies in step is itself a kind of transaction processing, because a change must reach every copy, or none of them, for the copies to agree.
Check yourself. T1 holds a lock on record X and is waiting for record Y. T2 holds a lock on Y and is waiting for X. What has happened, and how is it resolved?
Show the answer
This is deadlock: each transaction waits for the other forever. The database rolls one of them back, releasing its lock, so the other can finish, and then restarts the one it rolled back.
Reference
Key algorithms and definitions
| Term or algorithm | What it means | Example | Cost or rule to learn |
|---|---|---|---|
| SELECT … WHERE | Choose fields and filter rows | WHERE Score >= 50 | AND needs both; OR needs either |
| LIKE and BETWEEN | Pattern match and inclusive range | LIKE 'C%' | % any characters, _ one |
| INNER JOIN … ON | Match rows on a key | Pupils.Form = Forms.Form | No ON gives |
| Aggregates | COUNT, SUM, AVG, MAX, MIN | AVG(Score) = 59 | COUNT counts rows |
| GROUP BY | One result row per group | Pupils per form | HAVING filters groups |
| INSERT, UPDATE, DELETE | Change stored data | SET Score = Score + 5 | Always check the WHERE |
| Transaction | Operations as one unit | A bank transfer | COMMIT or ROLLBACK |
| ACID | Atomic, consistent, isolated, durable | Transfer never half done | Log makes it durable |
| Record locking | Others wait for a locked record | T2 waits for T1 | Risk of deadlock |
| Serialisation | Same result as one at a time | Timestamp ordering | Late transactions restart |
Programming task
Programming task: a lost update simulator
Aim
Write a Python program that simulates two transactions adding to the same balance. It must run them interleaved without locking, and again with record locking, printing each step and the final balance, and reporting how much money was lost.
Design
Each transaction is three steps: read the stored balance into a local copy, add its amount to the copy, and write the copy back. A schedule is a list saying which transaction takes its next step. Without locking, the schedule interleaves the reads before the writes. With locking, a transaction must take a lock before reading and release it after writing. A transaction that finds the lock taken must wait, so its step is skipped and retried.
The simulator stores the shared balance in one variable and each transaction's local copy in a dictionary. It prints the action and the stored balance after every step, so the lost update can be seen happening.
Code
def simulate(balance, amounts, schedule, locking):
local = {}
lock = None
step = {t: 0 for t in amounts}
queue = list(schedule)
while queue:
t = queue.pop(0)
if locking and step[t] == 0 and lock not in (None, t):
print(t, "waits for the lock")
queue.append(t)
continue
if step[t] == 0:
if locking:
lock = t
local[t] = balance
print(t, "reads", balance)
elif step[t] == 1:
balance = local[t] + amounts[t]
print(t, "writes", balance)
if locking:
lock = None
step[t] += 1
return balance
amounts = {"T1": 50, "T2": 20}
schedule = ["T1", "T2", "T1", "T2"]
for locking in (False, True):
final = simulate(100, amounts, schedule, locking)
lost = 100 + sum(amounts.values()) - final
print("locking" if locking else "no locking", "final", final, "lost", lost)
The schedule says T1 reads, then T2 reads, then T1 writes, then T2 writes. With locking on, T2's read finds the lock held by T1. So T2 is sent to the back of the queue, and retries after T1 has written and released the lock.
Testing
| Test | Input | Expected output | Why this test |
|---|---|---|---|
| 1 | £100, T1 +£50, T2 +£20, no locking | Final £120, lost £50 | Matches the lost update example |
| 2 | £100, T1 +£50, T2 +£20, locking | Final £170, lost £0 | Locking keeps both updates |
| 3 | £500, T1 +£200, T2 +£100, no locking | Final £600, lost £200 | Matches worked example 13 |
| 4 | £500, T1 +£200, T2 +£100, locking | Final £800 | Matches worked example 14 |
| 5 | Schedule T1, T1, T2, T2, no locking | Final £170 | Running one after another loses nothing |
| 6 | T1 adds £0 | Final £120 either way | Nothing to lose |
| 7 | T2 adds a negative amount, −£30, no locking | Final £70, T1's £50 lost | Withdrawals are lost in the same way |
Evaluation
The simulator reproduces the lost update and shows record locking preventing it, with the step-by-step output making the cause clear. Test 5 confirms that the problem comes from interleaving, not from the transactions themselves.
The simulator handles only two transactions and one record, so it cannot show deadlock. An improvement would add a second record, and a schedule in which each transaction locks one record and then requests the other. It would also detect when every transaction is waiting.
Practice
Practice ladder
Rung 1: Recall and fluency
Q1. State what each of the four ACID properties means.
Worked solution to Q1
Atomicity means a transaction happens completely or not at all. Consistency means it leaves the database in a valid state. Isolation means simultaneous transactions do not interfere, and durability means committed changes survive a crash.
Q2. Describe what the clause ORDER BY Score DESC does.
Worked solution to Q2
It sorts the rows of the result by the Score field in descending order, so the highest score comes first. Without DESC, the rows would be sorted from the lowest score upwards.
Q3. Explain the difference between COMMIT and ROLLBACK.
Worked solution to Q3
COMMIT makes every change in the transaction permanent. ROLLBACK undoes every change made since the transaction began, returning the database to the state it was in before the transaction started.
Rung 2: Application
Q4. Write a query to list the names of pupils with scores between 40 and 60, sorted by name, and give the result.
Worked solution to Q4
The query is SELECT Name FROM Pupils WHERE Score BETWEEN 40 AND 60 ORDER BY Name. Ben, with 45, and Dev, with 51, are in the range, so the result is Ben then Dev.
Q5. Write a query to count the pupils who scored at least 50, and state what it returns.
Worked solution to Q5
The query is SELECT COUNT(*) FROM Pupils WHERE Score >= 50. Ava, Cara and Dev meet the condition, so it returns 3. The WHERE clause is applied before the rows are counted.
Q6. Which names does WHERE Name LIKE '%a' return from the Pupils table?
Worked solution to Q6
The pattern matches any name ending in a, since % stands for any characters before it. Ava and Cara end in a, so those two names are returned.
Q7. Write a query that lists each tutor with the number of pupils they have.
Worked solution to Q7
The query is SELECT Tutor, COUNT(*) FROM Pupils INNER JOIN Forms ON Pupils.Form = Forms.Form GROUP BY Tutor. Joining brings in the tutor, so Ms Khan has 3 pupils and Mr Lee has 2.
Rung 3: Analysis
Q8. A query joins 120 pupils to 6 forms without an ON condition. How many rows does it give, and how many should it give?
Worked solution to Q8
Without a condition, every pupil pairs with every form: 120 × 6 = 720 rows. With the condition, each pupil matches only their own form, so the correct join gives 120 rows.
Q9. An account holds £300. T1 adds £100 and T2 subtracts £40, interleaved without locking, T2 writing last. Find the final balance and the money lost.
Worked solution to Q9
Both read £300. T1 writes £400, then T2 writes 300 − 40 = £260 over it. The correct balance is £360, so T1's £100 has been lost.
Q10. Explain why WHERE cannot be used to find forms with more than two pupils.
Worked solution to Q10
WHERE tests each row before the rows are grouped, so it cannot see how many rows a group has. A condition on a group's count must go in a HAVING clause after GROUP BY.
Q11. A transfer of £30 from A (£90) to B (£60) fails after the first update, and the database has no atomicity. Find the balances and the total.
Worked solution to Q11
Account A falls to 90 − 30 = £60, but B stays at £60, so the total is £120. Before the transfer it was £150, so £30 has vanished. Atomicity would roll the first update back.
Rung 4: Stretch
Q12. Explain how record locking can cause deadlock, and how a database recovers from it.
Worked solution to Q12
If T1 locks A and waits for B while T2 locks B and waits for A, neither can continue. The database detects the cycle of waiting, rolls one transaction back to release its locks, and restarts it.
Q13. Explain how timestamp ordering keeps transactions serialisable without locks.
Worked solution to Q13
Each transaction gets a timestamp when it starts, and each record stores the timestamps of its last read and write. A transaction trying to change a record already used by a later one is rolled back and restarted, so changes always follow timestamp order.
Q14. Why does the money lost in an interleaved update not depend on the starting balance? Use the derivation.
Worked solution to Q14
The interleaved balance is b + a₂ and the correct one is b + a₁ + a₂, so the difference is always a₁. The starting balance b cancels out, so the whole of the overwritten transaction's change is lost whatever the balance.
Exam practice
Exam technique and worked answer workshop
Write SQL clauses in the standard order, SELECT, FROM, WHERE, GROUP BY, ORDER BY, and put text values in single quotation marks. For a join, always include the ON condition, naming each field with its table when both tables use the same name.
When asked what a query returns, work through it as the database does: join first, then filter with WHERE, then group, then sort. Write out the rows kept at each stage.
For transaction questions, use a timeline of reads and writes. Show which values each transaction reads and writes, and name the problem, such as a lost update or deadlock, and the method that prevents it.
Exam question 1 (4 marks · Paper 01 · about 5 minutes)
Using the Pupils table, write an SQL query that lists the names and scores of pupils in form 12A with a score over 50, highest first. State the result.
Mark scheme for exam question 1
- B1 SELECT Name, Score FROM Pupils
- B1 WHERE Form = '12A' AND Score > 50
- B1 ORDER BY Score DESC
- B1 Cara 88, then Ava 72
Exam question 2 (5 marks · Paper 01 · about 7 minutes)
(a) Write an SQL query that lists each pupil's name with the name of their tutor, using the Pupils and Forms tables. [3]
(b) State how many rows the query would return if the ON condition were left out, and explain why. [2]
Mark scheme for exam question 2
- B1 SELECT Name, Tutor
- B1 FROM Pupils INNER JOIN Forms
- B1 ON Pupils.Form = Forms.Form
- B1 10 rows
- B1 every one of the 5 pupils is paired with each of the 2 forms
Exam question 3 (5 marks · Paper 01 · about 7 minutes)
(a) Write a query that gives the number of pupils and their average score for each form. [3]
(b) State the result. [2]
Mark scheme for exam question 3
- B1 SELECT Form, COUNT(*), AVG(Score)
- B1 FROM Pupils
- B1 GROUP BY Form
- B1 12A: 3 pupils, average 66.33
- B1 12B: 2 pupils, average 48
Exam question 4 (4 marks · Paper 01 · about 5 minutes)
(a) Write an SQL command that adds 5 marks to the score of every pupil in 12B. [2]
(b) State the effect of the same command with the WHERE clause left out. [1]
(c) Write a command that removes every pupil with a score below 40. [1]
Mark scheme for exam question 4
- B1 UPDATE Pupils SET Score = Score + 5
- B1 WHERE Form = '12B'
- B1 every pupil's score would increase by 5
- B1 DELETE FROM Pupils WHERE Score < 40
Exam question 5 (6 marks · Paper 01 · about 9 minutes)
A ticket website lets thousands of customers book seats at the same time. Discuss how transaction processing keeps the bookings correct.
Mark scheme for exam question 5
Level 3 (5–6 marks): a clear explanation of the ACID properties and of concurrency control, linked to seat booking. It includes the double-booking problem and at least one method of preventing it, with its drawbacks. The answer reaches a justified conclusion. It is well organised and uses technical terms accurately.
Level 2 (3–4 marks): a correct description of some ACID properties or of locking, with some link to booking seats. The analysis is limited.
Level 1 (1–2 marks): some relevant points, such as that bookings should be saved, with little application. The answer may lack structure.
0 marks: no response or no response worthy of credit.
Indicative content:
- each booking, taking payment and marking the seat as sold, is one transaction
- atomicity means a customer is never charged without getting the seat, or the reverse
- consistency keeps the rules true, such as a seat being sold at most once
- isolation stops two customers' bookings interfering
- without control, two customers could both read a seat as free and both book it
- record locking makes the second customer wait until the first booking commits
- locking can cause deadlock, which the system detects and resolves by rolling one back
- timestamp ordering is an alternative that restarts conflicting transactions
- durability means a confirmed booking survives a crash
- conclusion: ACID transactions with locking or timestamps make simultaneous booking safe
Annotated model answer: exam question 5
"Each booking is one transaction: take the payment and mark the seat as sold. Atomicity means both happen or neither does, so no customer pays for a seat they do not get." (Atomicity, applied to booking.)
"Without control, two customers could both read seat 14 as free and both book it. Record locking stops this. The first booking locks the seat, and the second customer must wait until it commits, by which time the seat shows as sold." (The concurrency problem and locking.)
"Locking can cause deadlock if two bookings each hold a seat the other wants. The system detects this and rolls one back. Timestamp ordering is an alternative that restarts a conflicting booking instead of making it wait." (A drawback and an alternative.)
"Durability means a confirmed booking is written to permanent storage, so it survives a crash. Together these properties let thousands of people book at once safely." (Durability and a conclusion.)
This answer reaches Level 3 and scores 6 marks. It links each property and method to the booking system and weighs a drawback.
Exam question 6 (5 marks · Paper 01 · about 7 minutes)
An account holds £500. Transaction T1 adds £200 and T2 adds £100. Both read the balance before either writes.
(a) Give the final balance, and explain how the problem arises. [3]
(b) Explain how record locking prevents it. [2]
Mark scheme for exam question 6
- B1 £600
- B1 both read £500, T1 writes £700, then T2 writes £600 over it
- B1 T1's update is lost; the correct balance is £800
- B1 T1 locks the record before reading, so T2 must wait
- B1 T2 then reads £700 after T1 commits and writes £800
Exam question 7 (4 marks · Paper 01 · about 5 minutes)
(a) Using a bank transfer as an example, explain atomicity. [2]
(b) Explain what is meant by durability. [2]
Mark scheme for exam question 7
- B1 a transaction is either completed in full or not at all
- B1 money taken from one account is always added to the other, or both updates are rolled back
- B1 once a transaction is committed, its changes are permanent
- B1 they survive a crash or power cut, because they are written to permanent storage or a log
Exam question 8 (7 marks · Paper 02 · about 10 minutes)
The pupils' names and scores are stored in arrays name and score, with n pupils. Write a function averageAbove(score, n, minimum) that returns the average of the scores that are at least minimum, or 0 if there are none. State what it returns for a minimum of 50.
Mark scheme for exam question 8
- B1 a function header with the three parameters
- B1 a total and a count, both starting at 0
- B1 a loop over all n scores
- B1 each score compared with minimum, using >=
- M1 matching scores added to the total and counted
- B1 0 returned when the count is 0
- A1 otherwise total ÷ count returned, which is 70.33 for a minimum of 50
Annotated model answer: exam question 8
function averageAbove(score, n, minimum)
total = 0
count = 0
for i = 0 to n - 1
if score[i] >= minimum then
total = total + score[i]
count = count + 1
endif
next i
if count == 0 then
return 0
endif
return total / count
endfunction
The header earns the first mark and the two variables the second. The loop and the comparison earn the next two marks, and adding and counting the matches earns the method mark. Returning 0 when nothing matches avoids dividing by zero and earns a mark, and returning 211 ÷ 3 = 70.33 for a minimum of 50 earns the last. This is the same calculation as SELECT AVG(Score) FROM Pupils WHERE Score >= 50.
Connections
Synoptic link
SQL is a declarative language, one of the paradigms in Translators and programming paradigms. The tables it queries were designed in Databases and normalisation, and joins follow the foreign keys set up there.
Transaction processing runs inside the operating systems of Operating systems and applications, which also schedule many processes at once. The lost update is a form of race condition, the same problem that arises when threads share memory, and record locks work like the locks used in concurrent programming.
Synoptic question 1. A website handles 2,000 transactions a second, and 1 in 500 of them is rolled back by a deadlock. How many are rolled back each minute?
Answer to synoptic question 1
Each second, 2,000 ÷ 500 = 4 transactions are rolled back. In a minute that is 4 × 60 = 240, all of which the database restarts automatically.
Recap
Recap and next step
- SELECT chooses fields, FROM names the table, WHERE filters rows with AND, OR, NOT, LIKE and BETWEEN, and ORDER BY sorts.
- INNER JOIN … ON matches rows on a key; without the condition, the result has |A| × |B| rows.
- COUNT, SUM, AVG, MAX and MIN summarise rows; GROUP BY gives one row per group, and HAVING filters groups.
- CREATE TABLE defines tables; INSERT, UPDATE and DELETE change data, and UPDATE or DELETE without WHERE affects every row.
- A transaction is one unit, committed or rolled back, with the ACID properties: atomic, consistent, isolated and durable.
- Interleaved transactions can lose updates; record locking, serialisation, timestamp ordering and commitment ordering prevent it, and deadlocks are resolved by rolling back.
Next chapter: Networks, protocols and the internet looks at how the databases behind websites are reached, as requests and results travel across networks.
For your exam board
OCR A Level Computer Science (H446): this chapter covers section 1.3.2, Databases, in Component 01: SQL to interpret and modify data, and transaction processing, including ACID, record locking, redundancy, serialisation, timestamp ordering and commitment ordering.
AQA A Level Computer Science (7517): structured query language, including SELECT, INSERT, UPDATE and DELETE and the definition of tables, and the management of concurrent access with record locks, serialisation, timestamp ordering and commitment ordering, appear in the fundamentals of databases section, assessed on Paper 2.