SQL Queries, Joins, Indexes and Database Security

IB Computer Science · Option: Object-Oriented Programming and Databases

The anatomy of a query. SELECT names the columns wanted; FROM names the table; WHERE filters rows with a condition; ORDER BY sorts the result; GROUP BY collapses rows sharing a value so that aggregate functions — COUNT, SUM, AVG, MAX, MIN — can be applied per group, and HAVING filters those groups. Read a query in execution order, not written order: FROM and JOIN build the working table first, WHERE removes rows, GROUP BY and HAVING collapse and filter, ORDER BY sorts, and SELECT picks columns last. Most exam errors come from confusing WHERE (filters rows before grouping) with HAVING (filters groups after).

Joins. Normalisation splits data across tables; a join reassembles it. A foreign key in one table holds the primary key of another, and JOIN ... ON matches rows where they are equal. An inner join keeps only matching pairs — a student with no enrolments does not appear; a left join keeps every row of the left table, with empty values where there is no match, which is how you list students including those with no enrolments. Joining three tables chains two ON conditions. The join is what makes normalisation workable: data is stored once and reassembled on demand.

Indexes. Without an index, finding rows with a given value means scanning the whole table. An index is a separate sorted structure (typically a tree) on one column that lets the database jump to matching rows, so a search on an indexed column is logarithmic instead of linear. The cost: every insert, update or delete must also update the index, so writes slow down, and each index takes storage. The rule is to index columns used in WHERE and JOIN on tables that are read far more than written, and not to index everything.

Security and integrity. A database concentrates an organisation's most valuable data, so it needs layered protection: access rights per user or role (read-only for reporting, no access to salary tables for most staff); encryption of sensitive columns and of backups; audit logs of who read or changed what; backups stored off-site and tested by restoring them; and validation rules in the schema (types, ranges, foreign keys) so that bad data is rejected at the door. The classic attack is SQL injection: a program builds a query by pasting in text the user typed, so a user who types a fragment of SQL gets it executed with the program's rights. The defence is parameterised queries, which send user input as data that can never be interpreted as code. Finally, a centralised database gives a single version of the truth — but is also a single point of failure and a single target, which is the standard evaluation point.

THE JOIN: THE FOREIGN KEY IS THE BRIDGE BETWEEN TWO TABLES Student StudentIDNameYear S01An12 S02Binh11 S03Chi12 khoá chính: StudentID Enrolment StudentIDCourseMark S01Maths78 S01Physics65 S03Maths91 foreign key: StudentID → Student Join result NameCourseMark AnMaths78 AnPhysics65 ChiMaths91 Binh has no row: not enrolled STRUCTURE OF A QUERY — READ IN EXECUTION ORDER, NOT WRITING ORDER SELECT Name, Course, Mark← which columns (runs LAST) FROM Student JOIN Enrolment ON Student.StudentID = Enrolment.StudentID← which tables (FIRST) WHERE Mark ≥ 70 AND Year = 12← filter rows ORDER BY Mark DESC← sort · result: Chi 91, An 78 index on columns often filtered and joined: much faster search, but every insert or update must update the index → slower writes security: per-user permissions (read-only, only own tables), encrypt sensitive data, log access, off-site backups SQL injection: concatenating user input into a query → the attacker writes their own query; prevent with parameterization a centralized database has one source of truth, but is also a single point of failure and a single target
The top part of the figure has two tables: Student with primary key StudentID, and Enrolment with StudentID as a foreign key pointing back to Student, so one student can have many enrolment rows. The red line linking S01 in the two tables is the meaning of the join: each Enrolment row is matched with the Student row with the same StudentID, producing the result table on the right with name, course and mark. Binh does not appear in the result because there is no enrolment row for him — an inner join keeps only the matching pairs. The middle box dissects a query and reminds you to read in execution order rather than writing order: FROM and JOIN run first to build a temporary table, WHERE filters rows, ORDER BY sorts, and SELECT, which chooses the columns, runs last; with the condition mark at least 70 and year 12, the result is Chi 91 and then An 78. The bottom box gathers three frequently tested ideas. An index on columns often filtered and joined makes searching much faster, but every insert or update has to update the index, so writes are slower. Security includes per-user permissions, encrypting sensitive data, logging access and off-site backups. The red line is the classic vulnerability, SQL injection: concatenating user input straight into a query lets an attacker write their own query, and the defense is parameterization. The last sentence is the evaluation point about centralized databases: one source of truth, but also a single point of failure and a single target.

Worked example: Example 1 — writing three queries of increasing difficulty on two tables

Given two tables Student(StudentID, Name, Year) and Enrolment(StudentID, Course, Mark): (a) the name and mark of every year 12 student who has a mark of at least 70 in any course, sorted by mark in descending order; (b) the average mark for each course, showing only courses with an average above 75; (c) a list of all students, including those who have not enrolled in any course.

Solution

(a) Join, filter, sort.
SELECT Name, Course, Mark FROM Student JOIN Enrolment ON Student.StudentID = Enrolment.StudentID WHERE Year = 12 AND Mark ≥ 70 ORDER BY Mark DESC.
Execution order: build the joined table, keep the rows with year 12 and mark at least 70, sort in descending order, choose the three columns. With the data in the figure: Chi Maths 91, An Maths 78.

(b) Aggregate and filter groups.
SELECT Course, AVG(Mark) FROM Enrolment GROUP BY Course HAVING AVG(Mark) > 75.
The key point: the condition average above 75 applies to the group after aggregation, so HAVING must be used; writing WHERE AVG(Mark) is an error because WHERE runs before aggregation, when no average exists yet. With the data in the figure: Maths with an average of 84.5 is shown; Physics at 65 is excluded.

(c) Left join.
SELECT Name, Course FROM Student LEFT JOIN Enrolment ON Student.StudentID = Enrolment.StudentID.
An inner join would drop Binh because there is no matching enrolment row; a left join keeps every row of the left table, and Binh appears with an empty Course. The phrase including those who have not is the sign that signals a left join. To list only the students who have not enrolled, add WHERE Course IS NULL.

What the examiner looks for. The ON condition matching the key pair; distinguishing WHERE from HAVING; choosing the right type of join for the question; and checking the result on a small data set.

Worked example: Example 2 — diagnosing an attacked login page and a slow query

(a) A login page builds its query by concatenating strings: SELECT * FROM Users WHERE name = '[typed name]' AND password = '[typed password]'. Someone types the name admin' -- and any password, and gets into the admin account. Explain and fix. (b) A query looking up orders by customer ID on a table of 20 million rows takes 40 seconds; propose a fix and state its cost.

Solution

(a) Mechanism. After concatenation, the query becomes: SELECT * FROM Users WHERE name = 'admin' -- ' AND password = '...'. In SQL, two hyphens start a comment that runs to the end of the line, so the entire password check is ignored; the only remaining condition is name = 'admin', which is true, and that person gets in with admin rights. Root cause: the program lets the data the user types become code because it is pasted straight into the statement. A more dangerous variant could delete a table or read all the data.

Fix. Use a parameterized query: the statement is sent with placeholders, SELECT * FROM Users WHERE name = ? AND password = ?, and the values the user types are sent separately as data; the database never interprets them as SQL, so the string admin' -- is just a name that does not exist. In addition: do not store passwords as plain text but store hashes, and give the application account minimal privileges so that even if it is attacked, it cannot delete tables.

(b) Diagnosis. 40 seconds on 20 million rows means a full table scan: there is no index on the customer ID column. Create an index on CustomerID; the search becomes logarithmic, a few milliseconds. The cost: every new order has to update the index so inserts are slightly slower, and the index takes storage. For an orders table — read far more than written — the cost is worth paying. It is also worth adding: do not index every column, only the columns used in WHERE and JOIN, because a table with ten indexes writes very slowly.

Common mistake

Trap 1 — using WHERE for a condition on an aggregate function. WHERE runs before aggregation; a condition on a group must be HAVING.
Trap 2 — using an inner join when the question says including those who have none. An inner join drops rows that do not match; a left join is needed.
Trap 3 — saying indexes are always good. They slow writes and take storage; index only the filter and join columns on read-heavy tables.

Key takeaway

Lesson 4 summary. Four things to take into the exam room. One, read a query in execution order: FROM, WHERE, GROUP, HAVING, ORDER, SELECT. Two, an inner join keeps matching pairs, a left join keeps every row of the left table. Three, an index trades write speed for read speed. Four, SQL injection is data becoming code, prevented by parameterization; centralization is one source of truth and one target.

← Classes in Detail: Constructors, Static Members, UML and Program Structure · All IB Computer Science lessons · Practice IB Computer Science questions (free, instant scoring)