O Level Computer Science 2210 · Area 2 · Algorithms, programming and logic

Single-table databases and SQL queries

A single-table database is a grid of fields and records, and the exam asks you to build that grid from a description, choose a data type and a primary key for it, and then query it in SQL. You need to know what each clause does before you can predict what a query returns. Most marks are lost by choosing a data type that cannot hold the data, offering a field that is not unique as the primary key, or confusing COUNT with SUM.

Not started

Syllabus coverage

  • Define a single-table database from given data storage requirements, including fields, records and validation
  • Suggest suitable basic data types: text/alphanumeric, character, Boolean, integer, real and date/time
  • Understand the purpose of a primary key and identify a suitable primary key for a given database table
  • Read, understand and complete SQL scripts that query data stored in a single database table
  • Use SELECT, FROM, WHERE, ORDER BY ASCENDING, ORDER BY DESCENDING, AND, OR, COUNT, SUM and AVERAGE
  • Identify the output produced by an SQL statement applied to the given contents of a table

Part of the O Level Computer Science syllabus 2210.

One table, one primary key, one queryA primary key uniquely identifies a record, so no two rows can share one.SQL names the fields, the table and the condition - in that order.A single tableStudentIDSurnameYearClub1041Ahmed10Chess1042Bello11Debate1043Chen10ChessPrimary key: StudentID - unique, and never emptyEvery field has a data type: text, integer, date or BooleanSQL asks the questionSELECT Surname, ClubFROM Students WHERE Year = 10ORDER BY Surname ASCENDINGCOUNT, SUM and AVERAGEAND / OR join two conditions
A single database table drawn with its field names, the data type of each field and a primary key column marked, beside an SQL query and the rows that the query returns.

The shape of a single-table database

A database is an organised store of data that can be searched, sorted and updated without rewriting it. A single-table database keeps everything in one table: a grid in which each field is a column and each record is a row. Every record describes one thing - one bike, one booking, one pupil - and holds one value in every field.

Take a bike-hire company. Its table might be called Bike and have the fields BikeID, Model, FrameSize, HourlyRate, InService and LastServiced. One record is one bike: B104, Hybrid, 54, 6.50, TRUE, 14/02/2026. The table has the same shape all the way down, which is what makes it possible to search it by any field.

The design of the table - the list of fields and the data type of each - is settled before any data is entered. Changing it later means rebuilding the table and converting every record, so the design is where the care goes. There are no links to other tables in this topic: every field the data needs must be in this one table.

TermWhat it meansIn the bike table
TableThe whole grid of fields and records, holding one kind of thingEvery bike the company owns
FieldOne item of data about the thing a record describes; a column, defined onceModel, HourlyRate, InService
RecordOne complete row, with a value in every fieldB104, Hybrid, 54, 6.50, TRUE, 14/02/2026
Data storage requirementThe description of what must be stored, which you turn into fields'we need each bike's code, model, size, rate and whether it is available'

From a storage requirement to a field list

A question that asks you to define a database from given data storage requirements gives you a paragraph describing what has to be kept, and expects a list of fields with a data type for each. Work through the description and write down one field for every separate item of data it names.

Each field holds exactly one item. A field called BikeAndOwner cannot be sorted by owner or searched by bike, because the two values are stuck together in one cell. Split it into BikeID and OwnerName, and each can be used on its own. The same applies to an address: HouseNumber, Street, Town and Postcode are four fields, and only then can the table list everyone in one town.

Field names are single words with no spaces, written so their meaning is obvious - DateOfHire rather than DOH. The order of the fields does not change what the database can do, but it does change how easy the table is to read when you are working out a query's output by hand, so keep related fields together.

Finish by deciding which fields must have a value in every record. A field that can never be left empty is a design decision, and it is enforced by a validation rule rather than by hope.

  • One field for each separate item of data named in the requirement - count them and check the numbers match.
  • One item per field: split combined fields such as NameAndAddress into their parts.
  • Names are single words with no spaces and an obvious meaning.
  • Settle the field list before entering data; changing it later means rebuilding the table.
If the requirement says 'the date it was hired and the date it is due back', that is two fields, not one. Each date can then be compared with today's date separately.

Choosing a suitable data type

Every field has a data type, which decides what values it can hold and what can be done with them. The syllabus names six: text/alphanumeric, character, Boolean, integer, real and date/time. The test is always the data itself, not the name of the field.

Text/alphanumeric holds any combination of letters, digits and symbols and is never used in arithmetic: a model name, an address, a registration. Character holds exactly one character: a size code such as S, M or L, or a single letter grade. Boolean holds TRUE or FALSE and nothing else: whether a bike is in service, whether a fee has been paid.

Integer holds whole numbers: a frame size in centimetres, a number of gears, a quantity. Real holds numbers with a fractional part, so it is used for money and measurements: an hourly rate of 6.50, a distance of 12.4. Date/time holds a date, a time or both in a fixed format, so the database can put records in date order and work out how long ago something happened.

Two choices catch students out. A rate or price is real, because 6.50 has a fractional part that an integer would drop. A telephone number or bike code is text/alphanumeric even though it looks numeric, because it is never added up and it may begin with a zero, which an integer would remove.

Data typeWhat it can holdSuitable for
text/alphanumericAny letters, digits and symbols in any combinationModel, OwnerName, BikeID
characterExactly one characterFrameSizeCode S, M or L; a single grade
BooleanTRUE or FALSE onlyInService, FeePaid, IsAvailable
integerA whole number, positive or negativeNumberOfGears, Quantity, YearOfMake
realA number with a fractional partHourlyRate, Distance, Weight
date/timeA date, a time, or bothLastServiced, DateOfHire, TimeOut

The primary key

A primary key is a field that uniquely identifies each record. No two records may hold the same value in that field, and no record may leave it empty. Its purpose is to make every record findable and distinguishable: without it, two bikes of the same model and size would be indistinguishable, and a query could not reliably return the one that was hired.

A suitable primary key has three properties. Its value is unique to each record, it is present in every record, and it never changes during the life of the record. A code or ID that the organisation assigns satisfies all three, which is why tables almost always have a field such as BikeID, MemberID or OrderNumber.

Fields that describe the thing are poor keys. Model is not unique, because the company owns several bikes of the same model. OwnerName is not unique, because two owners can share a name. LastServiced is not unique, because several bikes can be serviced on the same day. If nothing in the table is unique, the answer is to add a new field - a code or an ID - rather than to force a key onto a field that cannot carry it.

The primary key also speeds up searching: the database can go straight to the record with a given key instead of reading every record in turn. That is a benefit of the key beyond simply telling records apart.

  • Unique to each record - no two records share a value.
  • Present in every record - a key can never be blank.
  • Never changes - a record keeps the same key for its whole life.
  • Usually a code or ID, not a description such as a name, model or date.
If a question asks you to identify a primary key and no field is unique, say that a new field should be added, such as HireID, and make that the key. That is a correct answer, not a failure.

Validation in a single-table database

Validation is an automatic check that data entered into a field is sensible before it is stored. It cannot tell whether a value is correct - a hire rate of 9.50 typed as 6.50 passes every check - but it stops the values that could not possibly be right.

A range check rejects a value outside stated limits: an HourlyRate below 0 or above 50, a FrameSize below 40 or above 62. A type check rejects the wrong kind of data, such as letters in an integer field. A presence check rejects a blank field that must have a value, such as BikeID. A length check rejects a value with too many or too few characters, such as a BikeID that must be exactly four characters. A format check rejects a value that does not match the expected pattern, such as a date that is not DD/MM/YYYY.

Validation rules belong to the design of the table, so they are written down with the fields. A question that asks for the design of a database often accepts a validation rule as part of the answer, and one example of a value that would be rejected proves you understand the rule.

CheckWhat it doesExample in the bike table
Range checkRejects a value outside stated limitsHourlyRate must be between 0 and 50
Type checkRejects data of the wrong typeNumberOfGears must be a whole number
Presence checkRejects a blank fieldBikeID cannot be empty
Length checkRejects a value of the wrong lengthBikeID must be exactly 4 characters
Format checkRejects a value that does not match a patternLastServiced must be DD/MM/YYYY

SELECT, FROM and WHERE

SQL queries a table and returns a result table. The three clauses that every query needs are SELECT, FROM and WHERE, and each answers a different question.

SELECT lists the fields that appear in the output. `SELECT Model, HourlyRate` returns those two columns; `SELECT *` returns every field. FROM names the table the data comes from: `FROM Bike`. WHERE gives a condition, and only the records for which the condition is true are returned: `WHERE HourlyRate < 10.00`.

The clauses are written in this order, each on its own line, and the statement ends with a semicolon in most conventions:

SELECT Model, HourlyRate FROM Bike WHERE InService = TRUE;

WHERE does not change the table - it filters the records that the query returns. Records that fail the condition are left out of the result, but they remain in the table. This is the single most useful fact for predicting output: apply WHERE first, and everything else to what survives.

SELECT decides the columns, WHERE decides the rows. Confusing the two is why students lose marks on output questions even when they can write the query.

Combining conditions with AND and OR

Two conditions can be combined in a WHERE clause. AND returns a record only when both conditions are true. OR returns a record when at least one of them is true.

`WHERE HourlyRate < 10.00 AND InService = TRUE` returns only bikes that are both cheap and in service - a bike that is cheap but out of service fails the second condition and is not returned. `WHERE FrameSize = 54 OR FrameSize = 58` returns bikes of either size, which is twice as many records as either condition alone would give.

There is no limit to the number of conditions that can be joined, but each one must be complete: `WHERE HourlyRate < 10.00 AND > 5.00` is not valid, because the second part has no field name. Write each condition in full: `WHERE HourlyRate > 5.00 AND HourlyRate < 10.00`.

When a question mixes AND and OR, work through the records one at a time and write down whether each condition is true. Do not try to do it in your head - the examiner is testing whether you can apply the logic, not how quickly you can do it.

ClauseReturns a record when
WHERE A AND BBoth A and B are true
WHERE A OR BA is true, or B is true, or both are true
WHERE A AND B OR CApply the conditions as written; test each record against the whole expression

Sorting the result with ORDER BY

ORDER BY puts the returned records in order. It is written after WHERE and names the field to sort on:

SELECT Model, HourlyRate FROM Bike WHERE InService = TRUE ORDER BY HourlyRate ASCENDING;

ASCENDING means smallest first - A to Z for text, earliest to latest for dates, lowest to highest for numbers. DESCENDING means largest first - Z to A, latest to earliest, highest to lowest. The syllabus writes both keywords in full, so `ORDER BY HourlyRate DESCENDING`, not `DESC`.

ORDER BY changes only the order of the records that WHERE has already selected. It never adds or removes a record, so a query with no WHERE and an ORDER BY returns the whole table, sorted. It also does not change the columns: the output still has exactly the fields named in SELECT.

If the sort field is not in the SELECT list, the records can still be sorted by it - the field is used for the order but does not appear in the output. This is a favourite trick in output questions, so read the SELECT list separately from the ORDER BY line.

COUNT, SUM and AVERAGE

These three functions replace a list of records with a single number. COUNT counts how many records were selected. SUM adds up the values in a numeric field. AVERAGE returns the mean of the values in a numeric field.

SELECT COUNT(BikeID) FROM Bike WHERE InService = TRUE;

This returns one number: how many bikes are in service. `SELECT SUM(HourlyRate) FROM Bike;` returns one number: the total of every rate in the table. `SELECT AVERAGE(HourlyRate) FROM Bike WHERE FrameSize = 54;` returns the mean rate of the size 54 bikes. COUNT can be used on any field, including text; SUM and AVERAGE only make sense on a numeric field.

COUNT counts records, not values, so `COUNT(BikeID)` and `COUNT(Model)` return the same number when no field is empty. SUM and COUNT are easy to swap under pressure: if the question asks 'how many', it is COUNT; if it asks 'how much in total', it is SUM; if it asks 'on average', it is AVERAGE.

A function in SELECT returns a single value, so the result table has one row and one column. Nothing else can be listed beside it unless the query groups the records, which is beyond a single-table query at this level.

FunctionReturnsExample
COUNT(field)The number of selected recordsSELECT COUNT(BikeID) FROM Bike WHERE InService = TRUE;
SUM(field)The total of the values in a numeric fieldSELECT SUM(HourlyRate) FROM Bike;
AVERAGE(field)The mean of the values in a numeric fieldSELECT AVERAGE(HourlyRate) FROM Bike WHERE FrameSize = 54;

Working out what a query returns

An output question gives you a table and a statement and asks for the result. Read the statement in the order the database applies it, which is not the order it is written: FROM first, then WHERE, then the SELECT list, then ORDER BY.

Start with FROM and put your finger on the table. Apply WHERE to every record and cross out the ones that fail; with AND, one failure is enough to remove the record, and with OR, one success is enough to keep it. Then take only the fields named in SELECT, in the order they are named. Finally sort what is left by the ORDER BY field, remembering that the sort field need not appear in the output.

If SELECT contains COUNT, SUM or AVERAGE, stop before the sorting stage: the answer is a single number, not a list. Count or add the records that survived WHERE, and write the number on its own.

Write the answer as a small table with the selected field names as headings. That shows the examiner you have applied SELECT, and it makes the effect of WHERE and ORDER BY visible in the rows.

  • FROM: identify the table and its records.
  • WHERE: test every record and discard the ones that fail.
  • SELECT: keep only the named fields, in the order named.
  • ORDER BY: sort the surviving records; ASCENDING smallest first, DESCENDING largest first.
  • If a function is used, the answer is one number rather than a list.

Key terms you must be able to define

Database
An organised store of data that can be searched, sorted and updated without being rewritten by hand.
Table
A grid of fields and records holding one kind of thing; a single-table database has exactly one.
Field
One item of data about the thing a record describes. It is a column, defined once for the whole table.
Record
One complete row of a table, holding one value in every field and describing one thing.
Primary key
A field whose value is unique to each record, present in every record and never changed, so it identifies the record.
Validation
An automatic check that data is sensible before it is stored, such as a range, type, presence, length or format check.
SQL
Structured query language: the language used to query a database table and return a result table.
WHERE
The SQL clause that gives a condition; only records for which the condition is true are returned.
ORDER BY
The SQL clause that sorts the returned records, ASCENDING from smallest to largest or DESCENDING from largest to smallest.

In context

2210 sets its questions inside systems a student already uses - a school network, a phone, a supermarket till, a vending machine, a website. These show how the theory is applied to a context you have not seen before, then you answer for the system you are given.

A bike-hire fleet

The table Bike holds BikeID, Model, FrameSize, HourlyRate, InService and LastServiced. `SELECT BikeID, Model FROM Bike WHERE InService = FALSE ORDER BY LastServiced ASCENDING;` returns the bikes that are out of service, oldest service date first, so the workshop knows which to look at next.

A school's library loans

One table, Loan, holds LoanID, BookTitle, BorrowerName, DateBorrowed and Returned. LoanID is the primary key because two borrowers can take the same title on the same day. `SELECT COUNT(LoanID) FROM Loan WHERE Returned = FALSE;` gives the number of books still out, and `SELECT BookTitle FROM Loan WHERE Returned = TRUE ORDER BY DateBorrowed DESCENDING;` lists the most recently returned titles first.

A sports club's members

The table Member holds MemberID, Surname, DateJoined, SubscriptionPaid and Age. MemberID is the key. `SELECT Surname FROM Member WHERE SubscriptionPaid = FALSE AND Age >= 18 ORDER BY Surname ASCENDING;` returns adult members who have not paid, in alphabetical order - the two conditions are joined with AND, so both must be true.

A café's daily sales

The table Sale holds SaleID, ItemName, Quantity, Price and TimeOfSale. `SELECT SUM(Quantity) FROM Sale WHERE ItemName = "Tea";` gives the number of teas sold, while `SELECT AVERAGE(Price) FROM Sale;` gives the mean price of everything sold. Neither returns a list, because each replaces the records with a single number.

Flashcards

Click a card to flip it. Mark honestly — the tracker uses this.

Q1What is the difference between a field and a record?
A field is a column - one item of data, defined once for the table. A record is a row - one complete set of values describing one thing.
Q2What is a single-table database?
A database that holds all of its data in one table, with no links to any other table, so every field needed must be in that table.
Q3Give the three properties of a suitable primary key.
It is unique to each record, it is present in every record, and it never changes.
Q4Why is a model name a poor primary key?
Several records can share the same model, so it does not identify one record uniquely. A code or ID assigned to each item does.
Q5Which data type would hold an hourly rate of 6.50, and why?
Real, because the value has a fractional part. An integer would store it as 6 and lose the 50p.
Q6Which data type holds only TRUE or FALSE?
Boolean, used for a field with exactly two possible values such as InService or SubscriptionPaid.
Q7What does WHERE do?
It gives a condition, and only the records for which the condition is true are returned. It does not change the table.
Q8What is the difference between AND and OR in a WHERE clause?
AND keeps a record only when both conditions are true. OR keeps it when either condition is true.
Q9What does ORDER BY HourlyRate DESCENDING do?
It sorts the returned records by hourly rate with the largest first. ASCENDING would put the smallest first.
Q10What is the difference between COUNT, SUM and AVERAGE?
COUNT gives the number of records selected; SUM adds the values in a numeric field; AVERAGE gives the mean of those values. Each returns a single number.
Q11Name four validation checks that could be applied to a database table.
Range (rate between 0 and 50), type (whole number), presence (key cannot be blank), length (code exactly four characters) and format (date as DD/MM/YYYY).
0 of 11 marked as known

Exam-style questions

8 questions, 28 marks. Write your answer and press Mark my answer — it is marked against the scheme and tells you which points you made and what would gain the next mark. You can still reveal the scheme and mark it yourself instead.

StateAO11 mark
State the name given to one complete row of a database table.

Mark scheme — tick each point you actually made

Examiner tip: Row = record, column = field. Learn the pair together so the terms cannot be swapped under pressure.
IdentifyAO12 marks
A table called Pupil has the fields PupilID, Surname, FirstName, DateOfBirth, TutorGroup and HasPaid. Identify a suitable primary key for the table and give one reason for your choice.

Mark scheme — tick each point you actually made

Examiner tip: Name the field, then say why it is unique. Mentioning why another field fails makes the reason convincing.
SuggestAO23 marks
A table stores data about the bikes a hire company owns, including the model name, the hourly rate, the frame size in centimetres and whether the bike is currently in service. Suggest a suitable data type for the model name, for the hourly rate and for the in-service field, giving a reason in each case.

Mark scheme — tick each point you actually made

Examiner tip: Give the type and the reason together. Each of these is decided by the shape of the data, not by the name of the field.
GiveAO24 marks
A table called Bike has the fields BikeID, Model, FrameSize, HourlyRate and InService. Give an SQL statement that returns the BikeID and Model of every bike with an hourly rate below 10.00 that is in service, with the cheapest bike first.

Mark scheme — tick each point you actually made

Examiner tip: SELECT names the fields, FROM the table, WHERE the conditions, ORDER BY the sort. ASCENDING is what puts the cheapest first, and both words are written in full.
IdentifyAO25 marks
The table Bike contains these records, listed as (BikeID, Model, FrameSize, HourlyRate, InService): (B101, Hybrid, 54, 6.50, TRUE); (B102, Road, 56, 12.00, TRUE); (B103, Hybrid, 54, 6.50, FALSE); (B104, Mountain, 48, 9.00, TRUE). Identify the output of this SQL statement, including the order of the records. SELECT Model, HourlyRate FROM Bike WHERE HourlyRate < 10.00 AND InService = TRUE ORDER BY HourlyRate DESCENDING;

Mark scheme — tick each point you actually made

Examiner tip: Test WHERE against every record before sorting, and apply ORDER BY only to the records that survive. The two Hybrids are not the same record - one is in service and one is not.
GiveAO24 marks
A table called Sale has the fields SaleID, ItemName, Quantity and Price. Give an SQL statement that returns the total number of records in the table, and a second statement that returns the average price of the items sold.

Mark scheme — tick each point you actually made

Examiner tip: COUNT counts records and AVERAGE returns the mean of a numeric field. Both return a single number, so there is no field list beside them in SELECT.
ExplainAO24 marks
A garage keeps its courtesy cars in a single table with the fields CarID, Model, Registration, DailyRate and Available. Explain why CarID is a more suitable primary key than Registration.

Mark scheme — tick each point you actually made

Examiner tip: Both fields look unique, so the mark is for the 'never changes' property. A registration can move between vehicles; an ID assigned by the garage cannot.
DescribeAO25 marks
A theatre sells tickets and stores each sale in a single table with the fields SaleID, Performance, SeatNumber, Price and Sold. Describe two validation checks that could be applied to this table as data is entered, and in each case give an example of data that would be rejected.

Mark scheme — tick each point you actually made

Examiner tip: Each check needs a field and a value it would reject. A format check on Performance, which must be DD/MM/YYYY, would also be accepted.

Exam technique for this topic

  • Choose the data type from the data and say why: a rate is real because it has a fractional part; a quantity is integer because it is whole; whether something is in service is Boolean because there are only two answers.
  • When you name a primary key, add the reason: the value is unique to each record, so no two records can be confused. Name a field that could not be unique - Model, Name, Date - and you will not get the mark.
  • Write SQL with each clause on a new line and the keywords in full: ORDER BY HourlyRate DESCENDING, never ORDER BY HourlyRate DESC. The syllabus spells both words out.
  • For an output question, apply WHERE before SELECT and ORDER BY before you write the answer, and show the result as a small table with the selected field names as headings.
  • Keep COUNT, SUM and AVERAGE apart by the question's wording: 'how many' is COUNT, 'total' is SUM, 'average' or 'mean' is AVERAGE.

Why students lose marks here

A student wroteA student chose Model as the primary key of the bike table, saying 'each model is different'.
Why it loses marksA hire fleet owns several bikes of the same model, so Model repeats. A primary key must be unique to each record, and Model cannot be.
The answer that scoresBikeID is the primary key: every bike has its own code, no two records share one, every record has one and it never changes. Model cannot be the key because two bikes of the same model would hold the same key value.
A student wroteA student stored HourlyRate as an integer 'because a rate is a number'.
Why it loses marksAn integer field holds whole numbers only, so a rate of 6.50 would be stored as 6 and the company would lose 50p on every hour hired.
The answer that scoresHourlyRate must be real, because it has a fractional part. Integer is right for a genuinely whole-number field such as FrameSize or NumberOfGears. The test is whether the data can have a decimal part, not whether it is a number.
A student wroteA student wrote `SELECT Model FROM Bike WHERE HourlyRate DESCENDING;`
Why it loses marksORDER BY is the clause that sorts, and it must name the field and then the direction. WHERE takes a condition, not a sort instruction, so the statement is not valid SQL.
The answer that scoresThe sort is a separate clause: `SELECT Model FROM Bike ORDER BY HourlyRate DESCENDING;`. WHERE would be used to choose which records appear, for example `WHERE InService = TRUE`.
A student wroteA student said `SELECT COUNT(HourlyRate) FROM Bike;` gives the total of all the hourly rates.
Why it loses marksCOUNT counts records. It returns the number of bikes in the table, not the sum of their rates.
The answer that scoresSUM adds the values: `SELECT SUM(HourlyRate) FROM Bike;` gives the total of the rates. COUNT gives how many records were selected, which is a count of bikes, not a total of money.
A student wroteA student read `ORDER BY LastServiced DESCENDING` as 'the oldest service first'.
Why it loses marksDESCENDING means largest first, so for dates it puts the most recent date at the top. The student has read DESCENDING as 'in order' rather than as a direction.
The answer that scoresDESCENDING puts the largest value first, so the latest service date appears at the top and the oldest at the bottom. ASCENDING would put the oldest first. The direction word, not the field name, decides which end comes first.

Where this fits in O Level Computer Science 2210

This page is one topic of Cambridge O Level Computer Science 2210. O Level Computer Science 2210 is the course home: every area and every topic in Cambridge's own order, the papers you sit and what each one tests, and the exam-practice tools. The full topic list, with each topic linked to its revision page, is on the O Level Computer Science 2210 syllabus page.