← IB Computer Science

A3.3 · Book pp. 186–194

Database programming

Your level

SQL lets you say what you want, and the database works out how to get it. You will run real queries in this chapter.

What you need to know

PointTopicLevel
A3.3.1Data language types within SQLSL + HL
A3.3.2Queries between two tablesSL + HL
A3.3.3Updating data with SQLSL + HL
A3.3.4Aggregate functionsHL
A3.3.5Database viewsHL
A3.3.6Transactions and data integrityHL

Keep the SQL lab open as you go. It runs a real database on your device, so nothing you do can break anything.

Next: DDL and DML →

A3.3.1 Data language types

PurposeCommands
Data definition language (DDL)Creates, changes and removes structuresCREATE, ALTER, DROP
Data manipulation language (DML)Adds, changes, deletes and retrieves dataSELECT, INSERT, UPDATE, DELETE
CREATE TABLE Employees (
    EmployeeID   INT PRIMARY KEY,
    LastName     VARCHAR(20),
    DepartmentID INT,
    FOREIGN KEY (DepartmentID) REFERENCES Department(DepartmentID)
);

ALTER TABLE Employees ADD Email VARCHAR(25);
ALTER TABLE Employees DROP COLUMN Email;
CREATE INDEX idx_last_name ON Employees (LastName);
DROP TABLE Employees;

✏️ Book correction

The book’s CREATE TABLE Employees makes DepartmentID the primary key, which would allow only one employee per department. EmployeeID should be the key, as above. Its ADD FOREIGN KEY line also needs brackets around the field name.

SELECT field1, field2
FROM table_name
WHERE condition
ORDER BY field1 DESC;

Next: queries →

A3.3.2 Queries between two tables

A JOIN combines rows from two tables, usually by matching a foreign key to a primary key.

SELECT Department.DepartmentName, Employees.LastName
FROM Employees
JOIN Department ON Employees.DepartmentID = Department.DepartmentID;
ToolExample
Remove duplicatesSELECT DISTINCT DepartmentID FROM Employees;
Relational operators= <> > < >= <=
A rangeWHERE Salary BETWEEN 40000 AND 50000
A listWHERE DepartmentID IN (1, 2)
Empty fieldsWHERE ManagerID IS NULL or IS NOT NULL
LogicWHERE (DepartmentID = 1 AND Salary > 40000) OR Salary < 36000
PatternWHERE LastName LIKE 'D_m%': % is any run of characters, _ is exactly one
OrderORDER BY DepartmentID, Salary DESC

WHERE filters rows before any grouping. HAVING filters groups after grouping, so it goes with GROUP BY.

✏️ Book corrections

  • Its first JOIN selects Employees.DepartmentName. That column belongs to Department.
  • Its HAVING example shows Salary where it needs AVG(Salary), both in the SELECT and in the HAVING line.
Try these in the lab
  1. List staff earning between 39000 and 45000.
  2. List the department name for each person with no manager.
  3. List last names with exactly three letters.

Answer for 3: SELECT LastName FROM Employees WHERE LastName LIKE '___';

Next: updates →

A3.3.3 Updating data

INSERT INTO Employees (EmployeeID, LastName) VALUES (8, 'Lim');
UPDATE Employees SET Salary = 40000 WHERE EmployeeID = 8;
DELETE FROM Employees WHERE EmployeeID = 8;

⚠️ Common mistake

UPDATE or DELETE with no WHERE changes every row. Run the same condition in a SELECT first.

Indexes and updates

Indexes speed up searches, but when an indexed column changes, the index must change too. This can slow the update and block other transactions. To manage this, batch updates, rebuild indexes regularly, or use partial indexes that cover only the most relevant records.

Next: aggregate functions →

Next: SQL lab →

HL A3.3.4 Aggregate functions

FunctionReturnsExample
SUMTotalSELECT SUM(Salary) FROM Employees;
COUNTNumber of recordsSELECT COUNT(EmployeeID) FROM Employees;
AVGAverageSELECT AVG(Salary) FROM Employees;
MINSmallestSELECT MIN(Salary) FROM Employees;
MAXLargestSELECT MAX(Salary) FROM Employees;

With GROUP BY, these work per group, which is useful for reports:

SELECT Department.DepartmentName, COUNT(Employees.EmployeeID) AS ECount
FROM Employees
JOIN Department ON Department.DepartmentID = Employees.DepartmentID
GROUP BY Department.DepartmentName;

✏️ Book correction

The book’s text calls the function AVERAGE, but the SQL keyword is AVG, as its own examples show.

Next: views →

HL A3.3.5 Database views

A view is a virtual table based on a SELECT. Different users can see different subsets of the same data.

TypeWhat it isStores data?
SimpleOne table, with no joins or aggregatesNo
ComplexSeveral tables, joins or aggregatesNo
MaterializedSaved results that are refreshed from time to timeYes

Advantages

  • Hides complexity and simplifies queries.
  • Security: limits which fields and records a user sees.
  • Data independence: tables can change while the view stays the same for users.
  • Consistency: everyone gets data presented in the same way.

A view is updatable only if it is a subset of one table (or updatable view), excluded fields allow NULL, and it has no joins, aggregates, DISTINCT or HAVING. Otherwise it is read-only.

✏️ Book note

The book says views increase performance. A normal view re-runs its query, so it simplifies your work but is not faster. The speed gain comes from materialized views. Note too that SQLite, used in the lab, has no materialized views.

Next: transactions →

HL A3.3.6 Transactions

A transaction is a sequence of operations executed as one unit of work. Four properties define it, known as ACID:

AtomicityAll of it succeeds, or none of it does
ConsistencyThe database stays valid and follows its rules
IsolationConcurrent transactions do not interfere with each other
DurabilityCommitted changes survive even if the system fails
BEGIN TRANSACTION;
UPDATE Employees SET Salary = Salary + 100 WHERE EmployeeID = 1;
UPDATE Employees SET Salary = Salary - 100 WHERE EmployeeID = 5;
COMMIT;      -- or ROLLBACK; to undo both

BEGIN TRANSACTION, COMMIT and ROLLBACK are transaction control language (TCL) commands.

⚠️ Common mistake

Use precise terms. “It stays safe” earns little, while “atomicity means a failed transfer is rolled back completely” earns marks.

Next: SQL lab →

SQL lab

The tables are Employees(EmployeeID, FirstName, LastName, Salary, ManagerID, DepartmentID) and Department(DepartmentID, DepartmentName). Choose an example, or write your own. All names and figures are made up.

🔬 Lab: real SQL

Nothing has run yet. The first run downloads a small database engine.

Next: review →

Quick quiz

1. Which is DDL?
2. Which is DML?
3. What does SELECT DISTINCT do?
4. Which pattern finds names ending in d?
5. In LIKE, the underscore matches…
6. How do you test for an empty field?
7. What happens if UPDATE has no WHERE?
8. Why can updating an indexed column be slow?

HL Extra questions

1. Which filters groups after aggregation?
2. Does a normal view store data?
3. Which ACID property means “all or nothing”?
4. Which property keeps committed work after a power cut?
5. What does ROLLBACK do?

Exam-style questions

These are written for this site in the style of Paper 1. Answer on paper first, then open the mark points.

  1. Outline the difference between DDL and DML. [2]

    Mark points
    • DDL creates, changes and removes structures, such as with CREATE [1].
    • DML adds, changes, deletes and retrieves data, such as with SELECT [1].
  2. Tables are Book(BookID, Title, AuthorID) and Author(AuthorID, LastName). Construct a query listing titles by the author “Rao”. [3]

    Mark points
    • SELECT Book.Title FROM Book [1]
    • JOIN Author ON Book.AuthorID = Author.AuthorID [1]
    • WHERE Author.LastName = 'Rao'; [1]
  3. Construct an SQL statement to raise the salary of engineer D894 by 300. [2]

    Mark points
    • UPDATE Engineer SET Salary = Salary + 300 [1]
    • WHERE EngineerID = 'D894'; [1]
  4. Construct SQL to add an integer field Experience to the Engineer table. [2]

    Mark points
    • ALTER TABLE Engineer [1]
    • ADD Experience INT; [1]
  5. Construct SQL to remove all students in year 13 from Student(StudentID, Year). [2]

    Mark points
    • DELETE FROM Student [1]
    • WHERE Year = 13; [1]

HL Exam-style questions

  1. Construct SQL to find the average salary in the Engineer table. [2]

    Mark points
    • SELECT AVG(Salary) [1]
    • FROM Engineer; [1]
  2. Discuss whether a view is physically stored in a database. [2]

    Mark points
    • A view is a virtual table: only its query definition is stored [1].
    • A materialized view is an exception, as it stores precomputed results [1].
  3. State the effect of rolling back a transaction, with an example of why it may be needed. [2]

    Mark points
    • All changes in the transaction are undone [1].
    • For example, a bank transfer fails after debiting one account [1].
  4. Describe the four properties that define a transaction. [4]

    Mark points
    • Atomicity: it completes fully or not at all [1].
    • Consistency: it leaves the database in a valid state [1].
    • Isolation: concurrent transactions do not interfere [1].
    • Durability: committed changes survive failures [1].