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.
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.