Skip to content

0478 · Unit 9 · Paper 2: Algorithms, programming and logic

Databases.

0478 · Unit 9 · Databases
Revisionbyexamplicity

Database tables, fields and records

§9 · Databases

A shop has to know what it sells, what each item costs and how many are left. It keeps this in a database: an organised collection of data. One of its tables is Stock; grey shows each field’s data type.

CodeItemNameCategoryPriceQuantityAvailable
texttexttextrealintegerBoolean
P01PenStationery1.5012TRUE
P02NotebookStationery3.004TRUE
P03CableElectronics6.500FALSE
P04MouseElectronics12.005TRUE
P05FolderStationery2.008TRUE

Stock: the same five records continue across both panels. Code identifies the matching row.

CodeItemNameCategory
texttexttext
P01PenStationery
P02NotebookStationery
P03CableElectronics
P04MouseElectronics
P05FolderStationery

Same Code, continued fields:

CodePriceQuantityAvailable
textrealintegerBoolean
P011.5012TRUE
P023.004TRUE
P036.500FALSE
P0412.005TRUE
P052.008TRUE

Records, fields and the primary key

To use a table you need names for its parts, and one field that never repeats, so each record can be found again.

Record = a row

All the data about one item. This table has 5 records. The heading row is not a record.

Field = a column

One item of data stored for every record, e.g. Price. This table has 6 fields.

Primary key

A field whose value is unique for every record, so it identifies each record. Here: Code.

Choose the most appropriate data type

The type decides what a field can hold and what can be done with it: Quantity can be added up, a phone number cannot. Choose each type from the values and how they are used.

Data typeUse it forStock field
Text / alphanumericletters, codes, or numbers with a leading zero or spaces (e.g. phone numbers)Code, ItemName, Category
Charactera single letter or symbol, e.g. a size code 'S'–
Booleanonly two values: TRUE / FALSE (yes / no)Available
Integerwhole numbers that may be calculated withQuantity
Realnumbers with a fractional part, e.g. moneyPrice
Date / timea date or a time–

Why Stock uses Code

Why not ItemName as the key?

Two items could one day have the same name, so ItemName may not stay unique. Each new item gets an unused Code, such as P01, so Code is always unique.

Why is Code text, not integer?

It contains a letter and is used as an identifier. A phone number is text too: it can start with 0.

Your turn

Bikes (a hire shop’s table):

BikeIDTypeGearsDayRateInService
B01City38.00TRUE
B02Mountain2115.00TRUE
B03City710.00FALSE
B04Road1812.50TRUE

1 How many records and how many fields does Bikes have?

2 Which field is the primary key? Why?

3 Give the data type of DayRate and of InService.

  1. 1
    4 records (rows), 5 fields (columns)
  2. 2
    BikeID: its value is unique for every bike (Type repeats: City)
  3. 3
    DayRate is real (money has a fractional part); InService is Boolean (only TRUE or FALSE)
Tick what you can do now
Practise with m26/22 Q8(a), Q8(b); s26/21 Q9(a)(i), Q9(a)(ii), Q9(b); s26/22 Q9(a); s26/23 Q8(a), Q8(b)
1 / 5
0478 · Unit 9 · Databases
Revisionbyexamplicity

Querying with SELECT, FROM and WHERE

§9 · Databases

You can check five items by eye, but not five thousand. A query asks the table a question for you. Its answer is a smaller table: the fields you name, from the records that match.

Every query reads this one table, Stock (5 records):

CodeItemNameCategoryPriceQuantityAvailable
P01PenStationery1.5012TRUE
P02NotebookStationery3.004TRUE
P03CableElectronics6.500FALSE
P04MouseElectronics12.005TRUE
P05FolderStationery2.008TRUE

Stock: the same five records continue across both panels. Code identifies the matching row.

CodeItemNameCategory
P01PenStationery
P02NotebookStationery
P03CableElectronics
P04MouseElectronics
P05FolderStationery

Same Code, continued fields:

CodePriceQuantityAvailable
P011.5012TRUE
P023.004TRUE
P036.500FALSE
P0412.005TRUE
P052.008TRUE

Items with no stock

SQL
SELECT ItemName
FROM Stock
WHERE Quantity = 0;

Result

ItemName
Cable
SQL
SELECT ItemName
FROM Stock
WHERE Quantity = 0;
Each Stock record tested
CodeItemNameSELECTQuantityWHEREIn result?
P01Pen12no
P02Notebook4no
P03Cable0yes
P04Mouse5no
P05Folder8no
Result
ItemName
Cable

Code and price of the pen: columns follow SELECT order; text values go in quotes

SQL
SELECT Code, Price
FROM Stock
WHERE ItemName = "Pen";

Result

CodePrice
P011.50
SQL
SELECT Code, Price
FROM Stock
WHERE ItemName = "Pen";
Each Stock record tested
CodeSELECTItemNameWHEREPriceSELECTIn result?
P01Pen1.50yes
P02Notebook3.00no
P03Cable6.50no
P04Mouse12.00no
P05Folder2.00no
Result
CodePrice
P011.50

Using a comparison operator

SQL
SELECT ItemName, Quantity
FROM Stock
WHERE Price >= 3.00;

Greater or equal is one of six comparison operators, and any WHERE condition can use them. Not equal is written <>.

equalnot equallessless or equalgreatergreater or equal
SQL=<><<=>>=

Result

ItemNameQuantity
Notebook4
Cable0
Mouse5

Without ORDER BY, the rows may come out in any order.

SQL
SELECT ItemName, Quantity
FROM Stock
WHERE Price >= 3.00;
Each Stock record tested
CodeItemNameSELECTPriceWHEREQuantitySELECTIn result?
P01Pen1.5012no
P02Notebook3.004yes
P03Cable6.500yes
P04Mouse12.005yes
P05Folder2.008no
Result
ItemNameQuantity
Notebook4
Cable0
Mouse5

Without ORDER BY, the rows may come out in any order.

Greater or equal is one of six comparison operators, and any WHERE condition can use them. Not equal is written <>.

equalnot equallessless or equalgreatergreater or equal
SQL=<><<=>>=

A Boolean field: TRUE and FALSE (and numbers) are not in quotes

SQL
SELECT ItemName
FROM Stock
WHERE Available = FALSE;

Result

ItemName
Cable
SQL
SELECT ItemName
FROM Stock
WHERE Available = FALSE;
Each Stock record tested
CodeItemNameSELECTAvailableWHEREIn result?
P01PenTRUEno
P02NotebookTRUEno
P03CableFALSEyes
P04MouseTRUEno
P05FolderTRUEno
Result
ItemName
Cable
Available is TRUE only when Quantity > 0, so WHERE Quantity = 0 and WHERE Available = FALSE find the same record.
Your turn

Bikes (a hire shop’s table):

BikeIDTypeGearsDayRateInService
B01City38.00TRUE
B02Mountain2115.00TRUE
B03City710.00FALSE
B04Road1812.50TRUE

1 Write the result of SELECT BikeID FROM Bikes WHERE Gears > 10;

2 Write a query to show the Type and DayRate of bike B03.

3 Write a query to show the BikeID of every bike that is not in service.

  1. 1
    B02, B04
  2. 2
    SELECT Type, DayRate FROM Bikes WHERE BikeID = "B03"; gives City 10.00
  3. 3
    SELECT BikeID FROM Bikes WHERE InService = FALSE; gives B03
Tick what you can do now
Practise with s26/22 Q9(b), Q9(c); m26/22 Q8(c); s26/21 Q9(c); m24/22 Q9(c) (older paper: Boolean filtering)
2 / 5
0478 · Unit 9 · Databases
Revisionbyexamplicity

Filtering with AND and OR

§9 · SQL conditions

A real question often has two parts: stationery that is running low, or anything electronic or cheap. AND keeps a record only when both conditions are true. OR keeps it when at least one is true, including when both are. Test the whole condition on each record in turn.

Every query reads this one table, Stock (5 records):

CodeItemNameCategoryPriceQuantityAvailable
P01PenStationery1.5012TRUE
P02NotebookStationery3.004TRUE
P03CableElectronics6.500FALSE
P04MouseElectronics12.005TRUE
P05FolderStationery2.008TRUE

Stock: the same five records continue across both panels. Code identifies the matching row.

CodeItemNameCategory
P01PenStationery
P02NotebookStationery
P03CableElectronics
P04MouseElectronics
P05FolderStationery

Same Code, continued fields:

CodePriceQuantityAvailable
P011.5012TRUE
P023.004TRUE
P036.500FALSE
P0412.005TRUE
P052.008TRUE

AND: a record must pass both tests

SQL
SELECT ItemName
FROM Stock
WHERE Category = "Stationery"
AND Quantity <= 5;
Each Stock record tested
CodeItemNameSELECTCategoryWHEREQuantityWHEREIn result?
P01PenStationery12no
P02NotebookStationery4yes
P03CableElectronics0no
P04MouseElectronics5no
P05FolderStationery8no

Result

ItemName
Notebook
SQL
SELECT ItemName
FROM Stock
WHERE Category = "Stationery"
AND Quantity <= 5;
Each Stock record tested
CodeItemNameSELECTCategoryWHEREQuantityWHEREIn result?
P01PenStationery12no
P02NotebookStationery4yes
P03CableElectronics0no
P04MouseElectronics5no
P05FolderStationery8no
Result
ItemName
Notebook

Notebook is the only record that passes both tests. Pen and Folder fail the quantity test; Cable and Mouse fail the category test. Passing one test is not enough for AND.

  • Notebook is the only record that passes both tests.
  • Pen and Folder fail the quantity test; Cable and Mouse fail the category test.
  • Passing one test is not enough for AND.

OR: a record must pass at least one test

SQL
SELECT ItemName
FROM Stock
WHERE Category = "Electronics"
OR Price < 2.00;

Result

ItemName
Pen
Cable
Mouse

Pen passes the price test; Cable and Mouse pass the category test.

SQL
SELECT ItemName
FROM Stock
WHERE Category = "Electronics"
OR Price < 2.00;
Each Stock record tested
CodeItemNameSELECTCategoryWHEREPriceWHEREIn result?
P01PenStationery1.50yes
P02NotebookStationery3.00no
P03CableElectronics6.50yes
P04MouseElectronics12.00yes
P05FolderStationery2.00no
Result
ItemName
Pen
Cable
Mouse

Pen passes the price test; Cable and Mouse pass the category test.

Each result row comes from one record: never put one item's name with another item's value. A record that passes both OR tests still appears only once.

  • Each result row comes from one record: never put one item's name with another item's value.
  • A record that passes both OR tests still appears only once.
Your turn

Bikes (a hire shop’s table):

BikeIDTypeGearsDayRateInService
B01City38.00TRUE
B02Mountain2115.00TRUE
B03City710.00FALSE
B04Road1812.50TRUE

1 Write the result of SELECT BikeID FROM Bikes WHERE Type = "City" AND InService = TRUE;

2 Write the result of SELECT BikeID FROM Bikes WHERE Type = "City" OR Gears > 20;

3 Write a query to show the BikeID of bikes with more than 5 gears that cost less than 13.00 a day.

  1. 1
    B01 (B03 is City but not in service)
  2. 2
    B01, B02, B03 (B01 and B03 are City; B02 has 21 gears)
  3. 3
    SELECT BikeID FROM Bikes WHERE Gears > 5 AND DayRate < 13.00; gives B03, B04

Without ORDER BY, SQL does not promise any order for the rows. The order shown in a result table here is only one possible order.

Tick what you can do now
Practise with s24/22 Q10(d) (older paper: AND); w24/23 Q11(b)(i) (older paper: filtered output)
3 / 5
0478 · Unit 9 · Databases
Revisionbyexamplicity

Sorting query results with ORDER BY

§9 · Databases

A price list is easier to read with the dearest item first, and a list of names in A to Z order. WHERE picks the records, SELECT picks the fields and ORDER BY sets the order of the rows. A sorted row moves as a whole: its values stay together.

Every query reads this one table, Stock (5 records):

CodeItemNameCategoryPriceQuantityAvailable
P01PenStationery1.5012TRUE
P02NotebookStationery3.004TRUE
P03CableElectronics6.500FALSE
P04MouseElectronics12.005TRUE
P05FolderStationery2.008TRUE

Stock: the same five records continue across both panels. Code identifies the matching row.

CodeItemNameCategory
P01PenStationery
P02NotebookStationery
P03CableElectronics
P04MouseElectronics
P05FolderStationery

Same Code, continued fields:

CodePriceQuantityAvailable
P011.5012TRUE
P023.004TRUE
P036.500FALSE
P0412.005TRUE
P052.008TRUE

Filter first, then sort by descending price

SQL
SELECT ItemName, Price
FROM Stock
WHERE Category = "Stationery"
AND Price <= 3.00
ORDER BY Price DESC;

Result

ItemNamePrice
Notebook3.00
Folder2.00
Pen1.50
SQL
SELECT ItemName, Price
FROM Stock
WHERE Category = "Stationery"
AND Price <= 3.00
ORDER BY Price DESC;
Each Stock record tested; ORDER BY Price DESC gives each kept record its place
CodeItemNameSELECTCategoryWHEREPriceSELECT · WHERE · ORDER BYIn result?
P01PenStationery1.503rd
P02NotebookStationery3.001st
P03CableElectronics6.50no
P04MouseElectronics12.00no
P05FolderStationery2.002nd
Result
ItemNamePrice
Notebook3.00
Folder2.00
Pen1.50
  1. 1
    WHERE keeps P01, P02 and P05, with prices 1.50, 3.00 and 2.00.
  2. 2
    DESC puts the highest price first: Notebook, Folder, Pen.
  3. 3
    The columns stay in SELECT order: ItemName, then Price.

Sort by a field that is not displayed

SQL
SELECT Code
FROM Stock
WHERE Category = "Stationery"
ORDER BY Quantity DESC;

Result

Code
P01
P05
P02

Sorted by Quantity (12, 8, 4), even though Quantity is not shown.

SQL
SELECT Code
FROM Stock
WHERE Category = "Stationery"
ORDER BY Quantity DESC;
Each Stock record tested; ORDER BY Quantity DESC gives each kept record its place
CodeSELECTCategoryWHEREQuantityORDER BYIn result?
P01Stationery121st
P02Stationery43rd
P03Electronics0no
P04Electronics5no
P05Stationery82nd
Result
Code
P01
P05
P02

Sorted by Quantity (12, 8, 4), even though Quantity is not shown.

ORDER BY Field ASC sorts smallest to largest (A → Z for text); DESC sorts largest to smallest (Z → A). ASC is the default if neither is written. “Alphabetical order” means ASC.
Your turn

Bikes (a hire shop’s table):

BikeIDTypeGearsDayRateInService
B01City38.00TRUE
B02Mountain2115.00TRUE
B03City710.00FALSE
B04Road1812.50TRUE

1 Write the result of SELECT BikeID, DayRate FROM Bikes ORDER BY DayRate DESC;

2 Write a query to show the Type of every bike in service, fewest gears first.

  1. 1
    B02 15.00; B04 12.50; B03 10.00; B01 8.00 (highest rate first)
  2. 2
    SELECT Type FROM Bikes WHERE InService = TRUE ORDER BY Gears ASC; gives City, Road, Mountain (3, 18, 21 gears)
Tick what you can do now
Practise with s26/23 Q8(c); m26/22 Q8(d); w25/22 Q7(c) (older paper: order by an undisplayed field); m25/22 Q8(c) (older paper: ordered numeric output)
4 / 5
0478 · Unit 9 · Databases
Revisionbyexamplicity

COUNT, SUM and defining a table

§9 · Databases

Sometimes the answer you want is one number, not a list: how many stationery items there are, or how many are in stock altogether. COUNT gives how many records match. SUM adds up one number field across the records that match.

Stock has five records. Its Stationery records are P01 (Quantity 12), P02 (4) and P05 (8); the other records are P03 (0) and P04 (5).

COUNT

Counts matching records. COUNT(*) counts every matching row; COUNT(FieldName) gives the same count here.

SUM

Finds the total of the values in one numeric field for the records that match.

The same condition: COUNT gives how many records

SQL
SELECT COUNT(Code)
FROM Stock
WHERE Category = "Stationery";

Result

COUNT(Code)
3

3 records match: P01, P02, P05.

SQL
SELECT COUNT(Code)
FROM Stock
WHERE Category = "Stationery";
Each Stock record tested
CodeCOUNTCategoryWHERECounted?
P01Stationeryyes
P02Stationeryyes
P03Electronicsno
P04Electronicsno
P05Stationeryyes
Result
COUNT(Code)
3

3 records match: P01, P02, P05.

…and SUM adds up their quantities

SQL
SELECT SUM(Quantity)
FROM Stock
WHERE Category = "Stationery";

Result

SUM(Quantity)
24

12 + 4 + 8 = 24 items.

SQL
SELECT SUM(Quantity)
FROM Stock
WHERE Category = "Stationery";
Each Stock record tested
CodeCategoryWHEREQuantitySUMAdded?
P01Stationery12yes
P02Stationery4yes
P03Electronics0no
P04Electronics5no
P05Stationery8yes
Result
SUM(Quantity)
24

12 + 4 + 8 = 24 items.

No WHERE: COUNT includes every record

SQL
SELECT COUNT(*)
FROM Stock;

Result

COUNT(*)
5

Every record, including Cable with Quantity 0.

  • WHERE runs first. COUNT or SUM then gives one result from the records kept: 3 records for COUNT, or 24 items for SUM(Quantity).
  • Output that one value, not the three rows.

Defining a table: fields, types, key and validation

Choose meaningful field names → a suitable data type for each → a unique primary key → validation rules for the data entered. In Stock, Code identifies an item, Quantity stores a whole-item count and Price allows a fractional amount.

Every query depends on choices made when the table was designed:

  1. 1
    Choose meaningful field names.
  2. 2
    Give each a suitable data type.
  3. 3
    Choose a unique primary key.
  4. 4
    Set validation rules for the data entered.

In Stock, Code identifies an item, Quantity stores a whole-item count and Price allows a fractional amount. Each row below is one check made as data is entered; a field can need more than one.

FieldValidation checkRule
Codepresence checkmust not be blank: it is the primary key
Codelength and format checkexactly 3 characters: “P” followed by two digits
Quantitytype check · range checkan integer · 0 or more
Pricerange checkgreater than 0

WHERE runs first. COUNT or SUM then gives one result from the records kept: 3 records for COUNT, or 24 items for SUM(Quantity). Output that one value, not the three rows.

Your turn

Bikes (a hire shop’s table):

BikeIDTypeGearsDayRateInService
B01City38.00TRUE
B02Mountain2115.00TRUE
B03City710.00FALSE
B04Road1812.50TRUE

1 Write the result of SELECT COUNT(BikeID) FROM Bikes WHERE InService = TRUE;

2 Write a query to find the total number of gears on the City bikes.

3 Suggest a validation check and rule for DayRate.

  1. 1
    3 (B01, B02, B04)
  2. 2
    SELECT SUM(Gears) FROM Bikes WHERE Type = "City"; gives 10 (3 + 7)
  3. 3
    range check: DayRate must be greater than 0
COUNT(FieldName) skips records where that field is NULL (empty). COUNT(*) counts every matching row. They agree here because no Code is missing.
Tick what you can do now
Practise with s26/22 Q9(a); s24/21 Q9(b) (older paper: SUM); s24/22 Q10(c) (older paper: COUNT/SUM purposes); w25/21 Q1 (older paper: SQL keyword matching)
5 / 5