A3.3 · Book pp. 186–194
Database programming
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
| Point | Topic | Level |
|---|---|---|
| A3.3.1 | Data language types within SQL | SL + HL |
| A3.3.2 | Queries between two tables | SL + HL |
| A3.3.3 | Updating data with SQL | SL + HL |
| A3.3.4 | Aggregate functions | HL |
| A3.3.5 | Database views | HL |
| A3.3.6 | Transactions and data integrity | HL |
Keep the SQL lab open as you go. It runs a real database on your device, so nothing you do can break anything.
A3.3.1 Data language types
| Purpose | Commands | |
|---|---|---|
| Data definition language (DDL) | Creates, changes and removes structures | CREATE, ALTER, DROP |
| Data manipulation language (DML) | Adds, changes, deletes and retrieves data | SELECT, 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; 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; | Tool | Example |
|---|---|
| Remove duplicates | SELECT DISTINCT DepartmentID FROM Employees; |
| Relational operators | = <> > < >= <= |
| A range | WHERE Salary BETWEEN 40000 AND 50000 |
| A list | WHERE DepartmentID IN (1, 2) |
| Empty fields | WHERE ManagerID IS NULL or IS NOT NULL |
| Logic | WHERE (DepartmentID = 1 AND Salary > 40000) OR Salary < 36000 |
| Pattern | WHERE LastName LIKE 'D_m%': % is any run of characters, _ is exactly one |
| Order | ORDER 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 toDepartment. - Its HAVING example shows
Salarywhere it needsAVG(Salary), both in the SELECT and in the HAVING line.
Try these in the lab
- List staff earning between 39000 and 45000.
- List the department name for each person with no manager.
- List last names with exactly three letters.
Answer for 3: SELECT LastName FROM Employees WHERE LastName LIKE '___';
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.
HL A3.3.4 Aggregate functions
| Function | Returns | Example |
|---|---|---|
SUM | Total | SELECT SUM(Salary) FROM Employees; |
COUNT | Number of records | SELECT COUNT(EmployeeID) FROM Employees; |
AVG | Average | SELECT AVG(Salary) FROM Employees; |
MIN | Smallest | SELECT MIN(Salary) FROM Employees; |
MAX | Largest | SELECT 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.
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.
| Type | What it is | Stores data? |
|---|---|---|
| Simple | One table, with no joins or aggregates | No |
| Complex | Several tables, joins or aggregates | No |
| Materialized | Saved results that are refreshed from time to time | Yes |
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.
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:
| Atomicity | All of it succeeds, or none of it does |
| Consistency | The database stays valid and follows its rules |
| Isolation | Concurrent transactions do not interfere with each other |
| Durability | Committed 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.
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.
Quick quiz
HL Extra questions
Exam-style questions
These are written for this site in the style of Paper 1. Answer on paper first, then open the mark points.
-
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].
-
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]
-
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]
-
Construct SQL to add an integer field Experience to the Engineer table. [2]
Mark points
- ALTER TABLE Engineer [1]
- ADD Experience INT; [1]
-
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
-
Construct SQL to find the average salary in the Engineer table. [2]
Mark points
- SELECT AVG(Salary) [1]
- FROM Engineer; [1]
-
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].
-
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].
-
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].