Skip to content

A.3 · Databases

IB Computer Science HLTopic 3

Video lesson for this topic Open the video page
5:36

Databases

A school library keeps loans in one spreadsheet. Each row has the student's name, form, the book and the date. When a student changes form, dozens of rows must…

English narration · English and 中文 subtitles you can switch

3.1

Scope and prerequisites

This handout teaches Theme A3, Databases, for the course first assessed in 2027: relational databases, design and normalisation, and SQL. Sections marked AHL are for Higher Level only.

Prerequisites: data types from B2 (integer, string, Boolean, real).

3.2

Why use a database?

One spreadsheet, many problems

A school library keeps loans in one spreadsheet: each row has the student's name, form, the book's title and author, and the date. When a student changes form, dozens of rows must be edited, and some are missed. Two rows now disagree about the same student. A database is designed to stop this.

Rows of small labelled drawers in a library card catalogue
A library card catalogue is a database on paper — records you can search and sort by index

Database fundamentals

A database 数据库 is an organised collection of data. A database management system 数据库管理系统 (DBMS) is the software that stores it, runs queries, controls access and makes backups.

Problem with flat files How a relational database helps
data redundancy 数据冗余: the same data stored many times each fact stored once
inconsistency 数据不一致: copies disagree one copy, so nothing to disagree
hard to search and combine SQL queries join tables
no control over who sees what user accounts and permissions

Tables, records and keys

A relational database 关系数据库 stores data in tables 表 (relations). Each record 记录 (row) is one item; each field 字段 (column, attribute) is one property.

Key Meaning Example
primary key 主键 a field whose value is unique for every record student_id
foreign key 外键 a field that holds the primary key of another table, linking them student_id in Loan
composite key 复合键 a primary key made of two or more fields (order_id, item_id)

Referential integrity 参照完整性 requires a non-null foreign key to match a referenced key (a primary or other suitable unique key); nullable foreign keys may represent no specified reference: a loan cannot refer to a student who does not exist.

A Customer table with primary key customer_id and an Order table whose foreign key points to it; an inner join gives 6 rows and a left join 7, because customer Ben has no orders
A foreign key links each order to its customer
Vocabulary Train
English
database/ˈdeɪtəbeɪs/
database management system/ˈdeɪtəbeɪs ˈmænɪdʒmənt ˈsɪstəm/
data redundancy/ˈdeɪtə rɪˈdʌndənsi/
inconsistency/ˌɪnkənˈsɪstənsi/
relational database/rɪˈleɪʃənl ˈdeɪtəbeɪs/
table/ˈteɪbl/
record/ˈrekɔːd/
field/fiːld/
primary key/ˈpraɪməri kiː/
foreign key/ˈfɒrən kiː/
composite key/ˈkɒmpəzɪt kiː/
referential integrity/ˌrefəˈrenʃl ɪnˈteɡrɪti/
3.3

Database design

Entities and relationships

An entity 实体 is a thing we store data about: a student, a book. An entity-relationship diagram 实体关系图 (ERD) shows the entities and how they are related.

An ER diagram: Student, with student_id (PK), name and year_group, makes many Loans; each Loan, with loan_id (PK), student_id (FK), book_id (FK) and date_out, is of one Book, with book_id (PK), title and author. Crow's feet mark the "many" ends
One student makes many loans; each loan is of one book
Relationship Meaning Example
one-to-one each A has one B a student and their locker
one-to-many one A has many B one student, many loans
many-to-many many A, many B students and books

A many-to-many relationship cannot be stored directly: it is split into two one-to-many relationships through a link table 连接表, here Loan.

Normalisation

Normalisation 规范化 organises tables to remove redundancy. Start from one unnormalised table:

Normalisation: one table where the customer name and phone repeat on every order is split into a separate ORDER table and CUSTOMER table, so each fact is stored once
Normalisation removes redundancy by splitting repeated data into its own table
order_id customer phone items
501 Li Na 1381 pen, ruler
502 Li Na 1381 pen
Form Rule Result
first normal form 第一范式 (1NF) every field holds one atomic value; no repeating groups one row per item: key (order_id, item)
second normal form 第二范式 (2NF) 1NF, and no non-key field depends on only part of a candidate key customer depends only on order_id: move it to an Order table; price depends only on item: move it to an Item table
third normal form 第三范式 (3NF) 2NF, with no transitive dependency of a non-key field on a candidate key phone depends on the customer, not the order: move it to a Customer table

Result in 3NF:

  • Customer(customer_id, name, phone)
  • Order(order_id, customer_id)
  • OrderLine(order_id, item_id, quantity)
  • Item(item_id, description, price)

Now Li Na's phone number is stored once. A short test for 3NF: every non-key field depends on "the key, the whole key, and nothing but the key".

Choosing data types

Each field needs a type, such as INTEGER, VARCHAR(50) (text up to 50 characters), DATE, BOOLEAN or DECIMAL(6,2). Phone numbers are stored as text, not integers: they can start with 0 and are never added up.

Vocabulary Train
English
entity/ˈentɪti/
entity-relationship diagram/ˈentɪti rɪˈleɪʃənʃɪp ˈdaɪəɡræm/
link table/lɪŋk ˈteɪbl/
normalisation/ˌnɔːməlaɪˈzeɪʃn/
first normal form/fɜːst ˈnɔːml fɔːm/
second normal form/ˈsekənd ˈnɔːml fɔːm/
third normal form/θɜːd ˈnɔːml fɔːm/
3.4

SQL

Querying data

SQL 结构化查询语言 (Structured Query Language) defines and queries relational databases. The examples use these tables:

Five steps in order: FROM and JOIN give all rows, WHERE drops rows, GROUP BY forms groups, HAVING drops groups, SELECT returns the answer.
The order a grouped query runs in: WHERE before the groups exist, HAVING after
Student
student_id name year_group
1 Ana 11
2 Ben 12
3 Chen 11
Book
book_id title author
10 Dune Herbert
11 Emma Austen
12 Holes Sachar
Loan
loan_id student_id book_id date_out
100 1 10 2026-09-01
101 1 12 2026-09-05
102 3 11 2026-09-06
SELECT name
FROM Student
WHERE year_group = 11
ORDER BY name DESC;

Result: Chen, Ana. WHERE filters rows; ORDER BY … DESC sorts Z to A.

SELECT Student.name, Book.title
FROM Loan
JOIN Student ON Loan.student_id = Student.student_id
JOIN Book ON Loan.book_id = Book.book_id;

Result: (Ana, Dune), (Ana, Holes), (Chen, Emma). A join 连接 combines tables by matching the foreign key with the primary key. Ben has no loans, so he does not appear.

SELECT student_id, COUNT(*) AS loans
FROM Loan
GROUP BY student_id;

Result: (1, 2), (3, 1). Aggregate functions 聚合函数 such as COUNT, SUM, AVG, MAX and MIN work on groups of rows.

Clause Use
WHERE filter rows: =, <>, >, LIKE 'D%', AND, OR
ORDER BY sort, ASC or DESC
GROUP BY make groups for aggregate functions
HAVING filter groups: HAVING COUNT(*) > 1

Changing data

INSERT INTO Book (book_id, title, author) VALUES (13, 'Wonder', 'Palacio');
UPDATE Student SET year_group = 12 WHERE student_id = 3;
DELETE FROM Loan WHERE loan_id = 100;

An UPDATE or DELETE without WHERE changes every row.

Transactions

A transaction 事务 is a group of operations that must all succeed or all fail, such as moving money: take it from one account and add it to another. Transactions follow ACID:

A transfer as one transaction: take 50 from account A and add 50 to account B; if both succeed, commit; if either fails, roll back so A gets its 50 back
All of it, or none of it
Property Meaning
atomicity all of it happens, or none of it
consistency the database moves from one valid state to another
isolation transactions running at once do not interfere
durability once committed, a change survives a crash
Explore

One source row, several matches

Each source row contributes one result per matching record. A left join retains an unmatched source row as one NULL-matched row.

Vocabulary Train
English
SQL/ˌes kjuː ˈel/
join/dʒɔɪn/
aggregate function/ˈæɡrɪɡeɪt ˈfʌŋkʃn/
transaction/trænˈsækʃn/
3.5

AHL: Alternative databases and data warehouses

Beyond relational

Relational databases suit structured data with fixed fields. Other models suit other data:

A long row of black server racks on a raised white floor in a data centre, packed with equipment and cables
Rows of servers in a data centre, like those used for massively parallel computing
Model Stores Suits
document flexible records, such as JSON documents product catalogues with different fields
key-value a value for each key shopping carts, session data
graph nodes and the links between them social networks, route finding
spatial locations and shapes maps and delivery zones

These NoSQL databases scale across many servers easily, but give up some of the checks, such as referential integrity, that a relational DBMS enforces.

Data warehouses

A data warehouse 数据仓库 collects historical data from many sources into one store for analysis. Data is extracted, cleaned into one format, and loaded (ETL: extract, transform, load), usually overnight.

Tills, website and stock system are extracted, transformed into one format and loaded overnight into a data warehouse used for large historical queries and data mining
Extract, transform, load
Operational database Data warehouse
purpose run the business now analyse trends over time
data current, changes constantly historical, mostly read-only
queries many small reads and writes few large, complex queries

Data mining looks for patterns in the warehouse, such as which products are bought together. Because the data is about real people, it must be kept secure and used within the law.

Vocabulary Train
English
data warehouse/ˈdeɪtə ˈweəhaʊs/
3.6

Practice

  1. State two problems of storing a school's data in one flat file.
  2. Define primary key and foreign key, with an example from the library tables.
  3. Explain why the many-to-many relationship between students and books needs the Loan table.
  4. A table has fields (booking_id, room, room_capacity, date). Explain why it is not in 3NF and normalise it.
  5. Write SQL to list the titles of all books by Austen.
  6. Write SQL to list the names of students in year 11 with the number of loans each has made.
  7. State the result of SELECT COUNT(*) FROM Loan WHERE book_id > 10; for the tables above.
  8. Write SQL to change the author of book 12 to 'L. Sachar'.
  9. Explain atomicity using a bank transfer.
  10. AHL Suggest a suitable database model for a social network, and explain your choice.
  11. AHL Explain two differences between a data warehouse and an operational database.

Answers.

  1. E.g. data redundancy, the same student stored in many rows; inconsistency when one copy is updated and others are not; hard to search or control access.
  2. A primary key uniquely identifies each record, such as book_id in Book. A foreign key is a field holding another table's primary key, such as book_id in Loan.
  3. One student borrows many books and one book is borrowed by many students. A relational table cannot store this directly; the link table turns it into two one-to-many relationships, each loan linking one student and one book.
  4. room_capacity depends on room, a non-key field: a transitive dependency. Split into Booking(booking_id, room, date) and Room(room, room_capacity).
  5. SELECT title FROM Book WHERE author = 'Austen';
  6. SELECT Student.name, COUNT(*) FROM Student JOIN Loan ON Student.student_id = Loan.student_id WHERE Student.year_group = 11 GROUP BY Student.name; giving (Ana, 2), (Chen, 1).
  7. Loans 101 (book 12) and 102 (book 11): 2.
  8. UPDATE Book SET author = 'L. Sachar' WHERE book_id = 12;
  9. The money must both leave one account and arrive in the other; if the system fails part-way, the whole transaction is undone, so money is never lost or created.
  10. A graph database: people are nodes and friendships are links, so queries such as "friends of friends" follow links directly.
  11. E.g. a warehouse holds historical data from many sources, an operational database current data; a warehouse is mostly read for large analysis queries, an operational database handles many small updates.
3.7

Exam tips

  • Keys: say the primary key is unique for each record; a foreign key links to a primary key in another table.
  • In normalisation answers, name the dependency you are removing, then show the new tables with their keys.
  • Write SQL keywords in capitals, put text in single quotes, and end each statement with a semicolon.
  • In a join, always give the ON condition matching the foreign key to the primary key.
  • Check UPDATE and DELETE statements for a WHERE clause.
  • Learn ACID as four words with one-line meanings, and illustrate with a transfer.
Was this helpful?

More topics in IB Computer Science HL

Log in or create account

IGCSE, A-Level & AP