A Global Language for Organised Data

Every country on earth keeps records. Tax authorities in Stockholm, hospital registries in Nairobi, shipping manifests in Singapore - all of them rely on structured collections of data that can be searched, sorted, and updated reliably. The tool that makes this possible is the database, and the language used to query most of the world's databases is SQL. Whether you are studying in London, Lagos, or Lima, the Cambridge IGCSE Computer Science (0478) syllabus expects you to understand how databases are designed, how data types are chosen, what makes a good primary key, and how to write queries that retrieve exactly the information you need.

This topic bridges the gap between abstract data storage and the real systems that power online banking, airline booking, school administration, and e-commerce across every continent. The concepts here are not theoretical curiosities. They are the practical foundation of how modern organisations manage information.

Database Fundamentals

A database is an organised collection of structured data, stored electronically so that it can be easily accessed, managed, and updated. At the IGCSE level, you will work primarily with single-table flat-file databases, though you should understand that real-world systems often use multiple linked tables (relational databases).

Key Terminology

Three terms form the vocabulary of every database discussion:

  • Table: The structure that holds all the data. Think of it as a grid - rows and columns - where each column represents a category of information, and each row represents one complete entry.
  • Record: A single row in the table. Each record holds all the data about one entity (one student, one product, one transaction).
  • Field: A single column in the table. Each field holds one category of data across all records (for example, "Surname" or "DateOfBirth").

Consider a school database tracking student enrolment. The table might look like this:

StudentIDFirstNameSurnameDateOfBirthYear Group
S001AmaraOkafor2011-03-1410
S002LiamChen2010-08-2211
S003SofiaPetrov2011-01-0510

Here, each row is a record (one student), and each column is a field (StudentID, FirstName, Surname, DateOfBirth, Year Group). The whole structure is the table.

Designing a Single-Table Database

When an exam question asks you to design a database table from a written description, follow these steps:

  1. Identify the entities being stored (books, patients, orders).
  2. List the fields needed for each entity - what information must be recorded?
  3. Choose an appropriate data type for each field.
  4. Select a primary key - a field (or combination) that uniquely identifies each record.
Exam Tip: Examiners often present a scenario (a library, a sports club, a veterinary clinic) and ask you to design a suitable table. Read the scenario carefully and extract every piece of data mentioned. If the scenario says "the club records each member's name, date of joining, and membership type," those are your fields - do not invent extras the scenario does not mention, and do not leave any out.

Data Types

Every field in a database must be assigned a data type that determines what kind of values it can store and what operations can be performed on it. Choosing the correct data type is a skill that Cambridge examiners test directly. A telephone number stored as an INTEGER would lose its leading zero. A price stored as TEXT could not be used in a SUM calculation. Precision here matters.

Data TypeDescriptionExample ValuesWhen to Use
TEXT / STRINGAny sequence of characters (letters, digits, symbols)"Amara", "42 High Street", "AB12 3CD"Names, addresses, descriptions, postcodes, phone numbers
CHAR(n)A fixed-length string of exactly n characters"M", "F", "GB"Gender codes, country codes, any field where the length never varies
INTEGERA whole number (no decimal places)17, 250, -3Quantities, ages, year groups, number of items in stock
REALA number with a decimal/fractional part9.99, 36.5, -0.75Prices, weights, temperatures, measurements
BOOLEANOne of two possible values: TRUE or FALSETRUE, FALSEYes/no fields: "IsMember", "HasPaid", "InStock"
DATE / TIMEA calendar date or clock time2025-09-01, 14:30:00Dates of birth, appointment times, order dates
Common pitfall: Telephone numbers and postcodes look like they contain numbers, but they must be stored as TEXT (or STRING). A phone number like 07123456789 would lose the leading zero if stored as INTEGER. A postcode like "SW1A 1AA" contains letters and a space - it cannot be an integer at all. The rule: if you never need to perform arithmetic on the value, it is almost certainly TEXT.

Primary Keys

A primary key is a field (or combination of fields) that uniquely identifies each record in a table. No two records can share the same primary key value, and the primary key field cannot be left empty (null).

Why Primary Keys Matter

Without a primary key, the database has no reliable way to distinguish one record from another. Imagine a school table where two students share the name "Maria Garcia." If the table has no unique identifier, searching for Maria Garcia would return both records with no way to tell which is which. The primary key solves this by guaranteeing that every record has a distinct identity.

Primary keys also enable fast retrieval. The database engine builds an index on the primary key, allowing it to locate a specific record without scanning every row in the table.

Natural vs. Artificial Keys

Sometimes a field in the data is naturally unique. An ISBN uniquely identifies a book. A national insurance number uniquely identifies a person in the UK. A passport number uniquely identifies a passport. These are natural keys.

Often, though, no single field in the data is guaranteed to be unique. Names repeat. Dates repeat. Addresses can be shared. In these cases, you create an artificial key - a field whose sole purpose is to provide a unique identifier. StudentID, ProductCode, OrderNumber: these are invented specifically to serve as primary keys.

Exam Tip: When asked to identify a suitable primary key, look for the field that is unique to every record and will never be empty. If no such field exists in the given data, state that an artificial primary key (such as a sequential ID number) should be created. Examiners award marks for recognising when a natural key is insufficient.

SQL: Structured Query Language

SQL is the standard language for interacting with databases. From small classroom exercises to vast commercial systems used by companies in Tokyo, Berlin, and Sao Paulo, SQL is the shared vocabulary. The IGCSE syllabus focuses on retrieval queries - statements that extract data from existing tables.

The SELECT Statement

The basic structure of an SQL query is:

SELECT field1, field2 FROM TableName WHERE condition ORDER BY field ASC;

Each clause plays a specific role:

  • SELECT - specifies which fields to display. Use * to select all fields.
  • FROM - identifies the table to query.
  • WHERE - filters the records returned based on one or more conditions. Optional.
  • ORDER BY - sorts the results by a specified field, either ASC (ascending, the default) or DESC (descending). Optional.

Comparison and Logical Operators

OperatorMeaningExample
=Equal toWHERE YearGroup = 10
<Less thanWHERE Price < 20.00
>Greater thanWHERE Stock > 0
<=Less than or equal toWHERE Age <= 16
>=Greater than or equal toWHERE Score >= 50
<>Not equal toWHERE Country <> 'UK'
LIKEPattern matching (use % as wildcard)WHERE Surname LIKE 'S%'
ANDBoth conditions must be trueWHERE Age > 14 AND Age < 18
ORAt least one condition must be trueWHERE Country = 'France' OR Country = 'Spain'
NOTReverses the conditionWHERE NOT HasPaid = TRUE

Aggregate Functions

SQL provides functions that perform calculations across multiple records:

  • COUNT(*) - returns the number of records matching the query.
  • SUM(field) - returns the total of all values in a numeric field.
  • AVG(field) - returns the arithmetic mean of all values in a numeric field.

These are often combined with WHERE to narrow the calculation. For instance, SELECT AVG(Score) FROM Results WHERE Subject = 'Physics' returns the average physics score.

Worked SQL Examples

The examples below use this sample table, Products:

ProductIDProductNameCategoryPriceInStock
P001Wireless MouseAccessories12.99TRUE
P002USB KeyboardAccessories18.50TRUE
P003Monitor StandFurniture34.00FALSE
P004Webcam HDAccessories29.99TRUE
P005Desk LampFurniture22.75TRUE

Example 1: Show the names and prices of all accessories, sorted by price from lowest to highest.

SELECT ProductName, Price FROM Products WHERE Category = 'Accessories' ORDER BY Price ASC;

ProductNamePrice
Wireless Mouse12.99
USB Keyboard18.50
Webcam HD29.99

Example 2: Count the number of products that are currently in stock.

SELECT COUNT(*) FROM Products WHERE InStock = TRUE;

Result: 4

Example 3: Show all products costing more than 15.00 that are in stock, sorted by price from highest to lowest.

SELECT * FROM Products WHERE Price > 15.00 AND InStock = TRUE ORDER BY Price DESC;

ProductIDProductNameCategoryPriceInStock
P004Webcam HDAccessories29.99TRUE
P005Desk LampFurniture22.75TRUE
P002USB KeyboardAccessories18.50TRUE

Example 4: Calculate the average price of all products.

SELECT AVG(Price) FROM Products;

Result: 23.646

Example 5: Find all products whose name starts with "W".

SELECT * FROM Products WHERE ProductName LIKE 'W%';

ProductIDProductNameCategoryPriceInStock
P001Wireless MouseAccessories12.99TRUE
P004Webcam HDAccessories29.99TRUE

Worked Exam-Style Questions

Question 1 - Designing a Table [6 marks]

A veterinary clinic wants to create a database to store information about the animals it treats. For each animal, the clinic needs to record: the animal's name, species (e.g. dog, cat, rabbit), date of birth, weight in kilograms, whether the animal has been vaccinated, and the owner's telephone number.

(a) Design a suitable database table. For each field, give a field name, a suitable data type, and identify the primary key. [5 marks]
(b) Explain why the animal's name would not be a suitable primary key. [1 mark]

Model answer (a):

Field NameData TypePrimary Key?
AnimalIDTEXTYes
AnimalNameTEXTNo
SpeciesTEXTNo
DateOfBirthDATENo
WeightREALNo
VaccinatedBOOLEANNo
OwnerPhoneTEXTNo

Note that AnimalID is an artificial primary key created because none of the given fields is guaranteed to be unique. OwnerPhone is stored as TEXT to preserve any leading zeros and because no arithmetic is performed on it.

Model answer (b): The animal's name would not be a suitable primary key because multiple animals could have the same name (two dogs both called "Max"), so it cannot uniquely identify each record.

Question 2 - Writing SQL [8 marks]

A school stores student exam results in a table called Results with the following fields: StudentID (TEXT), StudentName (TEXT), Subject (TEXT), Score (INTEGER), Grade (CHAR).

Write SQL queries to:
(a) Display the names and scores of all students who scored 70 or above in Mathematics, sorted by score from highest to lowest. [3 marks]
(b) Count the number of students who achieved a grade of 'A'. [2 marks]
(c) Display all fields for students who scored less than 40 in either English or Science. [3 marks]

Model answer (a):

SELECT StudentName, Score FROM Results WHERE Subject = 'Mathematics' AND Score >= 70 ORDER BY Score DESC;

Model answer (b):

SELECT COUNT(*) FROM Results WHERE Grade = 'A';

Model answer (c):

SELECT * FROM Results WHERE Score < 40 AND (Subject = 'English' OR Subject = 'Science');

Exam Tip: Pay careful attention to brackets in SQL. In question (c), the parentheses around the OR condition are essential. Without them, the query would return all Science records regardless of score, because AND binds more tightly than OR. Examiners look for correct use of brackets in multi-condition queries.

Common Mistakes

  1. Choosing INTEGER for phone numbers or postcodes. These values contain leading zeros or letters that INTEGER cannot preserve. Always use TEXT for identifiers that are not used in arithmetic.
  2. Using a non-unique field as a primary key. A surname, a date of birth, or a city name can repeat across records. If no naturally unique field exists, create an artificial key.
  3. Forgetting ORDER BY defaults to ASC. If a question asks for results "in ascending order," ASC is technically optional but good practice to state. If the question says "highest first" or "largest to smallest," you must write DESC.
  4. Confusing COUNT with SUM. COUNT returns how many records match; SUM adds up the values in a numeric field. "How many students scored above 80" needs COUNT. "What is the total of all scores" needs SUM.
  5. Omitting quotes around text values in SQL. String comparisons require single quotes: WHERE Subject = 'Mathematics'. Numeric comparisons do not: WHERE Score >= 70. Mixing these up causes syntax errors.
  6. Ignoring brackets with AND/OR. SQL evaluates AND before OR. The query WHERE Score < 40 AND Subject = 'English' OR Subject = 'Science' does not do what most students intend. Use brackets to group the OR: WHERE Score < 40 AND (Subject = 'English' OR Subject = 'Science').

Self-Check Questions

  1. A bookshop stores data about its books. Each record includes the ISBN, title, author, price, and number of copies in stock. Which field should be the primary key? Justify your answer.
  2. A field stores whether a library book is currently on loan. What data type should this field be, and why?
  3. Write an SQL query to display the titles and authors of all books from the table Books where the price is less than 10.00, sorted alphabetically by title.
  4. Explain the difference between SELECT COUNT(*) FROM Orders WHERE Status = 'Shipped' and SELECT SUM(Quantity) FROM Orders WHERE Status = 'Shipped'.
  5. A database stores employee records. The fields are: EmployeeID, Name, Department, Salary, StartDate. Write an SQL query to find the average salary of employees in the "Engineering" department.
Answers at a glance:
1. ISBN should be the primary key because each book has a unique ISBN, so it uniquely identifies every record. Fields like title or author can repeat (different editions, same author writing multiple books).
2. BOOLEAN, because the field has exactly two possible states: on loan (TRUE) or not on loan (FALSE). No other data type fits a simple yes/no value as precisely.
3. SELECT Title, Author FROM Books WHERE Price < 10.00 ORDER BY Title ASC;
4. The COUNT query returns the number of orders with a status of 'Shipped' (how many shipped orders exist). The SUM query adds up the Quantity values across all shipped orders (the total number of items shipped). COUNT counts records; SUM totals a numeric field.
5. SELECT AVG(Salary) FROM Employees WHERE Department = 'Engineering';

Descarregar a aplicação na Google Play Store

Tudo o que precisas para te destacares no JAMB, WAEC e NECO.

Green Bridge CBT Mobile App
Assistente de Chat de Aprendizagem Personalizada com IA
Milhares de Questões de Exames Anteriores do IGCSE, JAMB, WAEC e NECO
Mais de 1200 Notas de Aula
Suporte Offline - Aprenda a Qualquer Hora, em Qualquer Lugar
Horário da Ponte Verde
Resumos de Literatura & Possíveis Perguntas
Acompanhe o Seu Desempenho e Progresso
Explicações Detalhadas para uma Aprendizagem Abrangente
Resumindo

A thorough set of revision notes on the Databases topic for Cambridge IGCSE Computer Science (0478), covering database fundamentals, data types, primary keys, and SQL queries with worked examples. The article includes exam-style questions with model answers, a common mistakes guide, and self-check exercises to consolidate understanding.