Querying with SQL

IGCSE Computer Science · Databases

The shape of a query

Every query in this syllabus follows the same pattern:

$$\textbf{SELECT } \text{fields} \ \textbf{ FROM } \text{table} \ \textbf{ WHERE } \text{condition} \ \textbf{ ORDER BY } \text{field}$$

SELECTwhich fields (columns) to show
FROMwhich table to take them from
WHEREwhich records (rows) to include — a condition
ORDER BYwhich field to sort the results on

The distinction that carries marks: SELECT chooses columns; WHERE chooses rows. They are doing different jobs on different axes of the table, and swapping them is a marked error.

$\textbf{SELECT} \ *$ means all fields.

A worked query

$\textbf{SELECT } \text{Surname, Mark}$

$\textbf{FROM } \text{Results}$

$\textbf{WHERE } \text{Mark} >= 50$

$\textbf{ORDER BY } \text{Mark } \textbf{DESC}$

Read it in the order the database works: take the table $\text{Results}$; keep only the rows where the mark is at least $50$; show only the two columns $\text{Surname}$ and $\text{Mark}$; sort them with the highest mark first.

$\textbf{ASC}$ sorts ascending (the default); $\textbf{DESC}$ sorts descending.

Conditions in WHERE

The comparison operators are the same as in programming: $=$, $<>$, $<$, $>$, $<=$, $>=$.

Conditions combine with AND and OR:

$\textbf{WHERE } \text{Mark} >= 50 \textbf{ AND } \text{Year} = 11$

Note that AND makes the result smaller (both must hold) while OR makes it larger (either will do). Students often reach for OR when they mean AND, and get far too many rows back.

Text values are put in quotation marks: $\textbf{WHERE } \text{Subject} = \text{"Physics"}$.

SUM and COUNT

The difference matters. $\textbf{SUM}(\text{Mark})$ on three marks of $40$, $50$ and $60$ gives $150$. $\textbf{COUNT}(*)$ on the same three records gives $3$.

So SUM answers "how much altogether?" and COUNT answers "how many?"

Why a database beats a set of separate files

SELECT chooses COLUMNS — WHERE chooses ROWS HoTen Diem Khoi MonHoc Lan 42 11 Physics Minh 78 11 Physics Hoa 35 10 Physics Nam 63 11 Physics SELECT HoTen, Diem WHERE Diem>=50 The area in BOTH COLOURS is the result: Minh 78 and Nam 63. Swapping the two keywords — using WHERE to choose columns — is an error that loses marks. Remember: SELECT goes VERTICALLY, WHERE goes HORIZONTALLY.
The two keywords work on two different axes of the same table — that is the surest way to remember.

Worked example: writing and reading a query

The table $\text{Results}$ has the fields $\text{FullName}$, $\text{Mark}$, $\text{Grade}$, $\text{Subject}$. (a) Write a query that shows the full name and mark of grade $11$ students who scored $50$ or above, sorted by mark in descending order. (b) Explain what each keyword does. (c) State the difference between SUM and COUNT.

Solution

(a) The query.

$\textbf{SELECT } \text{FullName, Mark}$

$\textbf{FROM } \text{Results}$

$\textbf{WHERE } \text{Mark} >= 50 \textbf{ AND } \text{Grade} = 11$

$\textbf{ORDER BY } \text{Mark } \textbf{DESC}$

Note the use of AND and not OR: the question requires both conditions to be satisfied together.

If OR were written, the result would include every student who scored $50$ or above in any grade, plus every grade $11$ student including those with low marks — far too many rows compared with what was asked.

(b) What each keyword does.

SELECT chooses which columns will be shown. Here it is the two columns $\text{FullName}$ and $\text{Mark}$ — the columns $\text{Grade}$ and $\text{Subject}$ are not shown, even though $\text{Grade}$ is used in the condition.

FROM states which table the data is taken from — here it is $\text{Results}$.

WHERE chooses which rows are kept. Only records satisfying both conditions get into the result.

ORDER BY sorts the result. $\textbf{DESC}$ is descending so the highest mark comes first; $\textbf{ASC}$ is ascending and is the default if nothing is written.

The most important point to grasp: SELECT chooses columns, WHERE chooses rows. They do two different jobs on two different axes of the same table.

(c) SUM and COUNT.

SUM adds the values in a numeric field. COUNT counts the records that satisfy the condition.

A concrete example. Suppose three students scored $40$, $50$ and $60$.

$\textbf{SELECT SUM}(\text{Mark})$ gives $150$ — the total of the three numbers.

$\textbf{SELECT COUNT}(*)$ gives $3$ — the number of records.

A concise way to tell them apart: SUM answers “how much in total?”, while COUNT answers “how many are there?”

Note that SUM can only be used on a numeric field; COUNT can be used with any table because it only counts rows.

Worked example: why use a database instead of many separate files

A club keeps its membership list in three separate files on three different machines. Explain four benefits of moving to a single database.

Solution

Benefit one — data is stored once.

The current problem. The same member appears in all three files. When that person moves house, staff must remember to correct all three places.

If just one file is missed, the club has two contradictory addresses for the same person — and nobody knows which is right.

The database solves this: the data is in one single place, so changing it once means every part sees the new version.

It also saves storage, because it does not keep three copies of the same thing.

Benefit two — validation is placed on the field.

In a database, the checks — range, length, type, presence, format — are attached to the field itself.

That means every entry is checked, no matter who types it or on which machine. With three separate files, each person could enter data by a different convention and nothing would stop them.

Benefit three — searching and sorting in any way.

A single query can pull out exactly what is needed: members who have not paid their fees, members in one district, members whose cards are about to expire — and sort by any field.

With separate files, every such question has to be done by hand: opening each file, scanning each line, copying out to somewhere else. It is both slow and easy to miss things.

Benefit four — a primary key ensures the right record is found.

A primary key is a unique field for each member, so the system can always retrieve exactly one record.

With separate files that have no member ID, two people with the same name cannot be told apart — and an update for one person may be written to the other by mistake.

Common mistake

Swapping the roles of SELECT and WHERE — writing WHERE to choose the columns to show. These two keywords work on two different axes of the same table. SELECT chooses COLUMNS, that is, which fields will appear in the result. WHERE chooses ROWS, that is, which records are kept. A column can perfectly well appear in WHERE without being shown: a query that filters by grade but only shows the full name and mark is perfectly normal. A sure way to remember: SELECT goes vertically, WHERE goes horizontally. The accompanying, subtler trap: using OR when AND is meant. A condition joined with AND makes the result smaller because both must be satisfied; joined with OR it makes the result larger because satisfying one is enough. For the requirement “grade $11$ students and scoring $50$ or above”, writing OR would return students from other grades as well as grade $11$ students with low marks.

Key takeaway

The query template: SELECT fields FROM table WHERE condition ORDER BY field. Remember firmly: SELECT chooses columns, WHERE chooses rows. $\textbf{SELECT} \ *$ takes every field; $\textbf{DESC}$ sorts descending, $\textbf{ASC}$ ascending and is the default. AND makes the result smaller, OR makes the result larger. SUM answers “how much in total?”, COUNT answers “how many are there?” A database beats separate files in four ways: data is stored once so there are no contradictions, validation is attached to the field, searching and sorting are fast in any way, and a primary key ensures the right record is retrieved.

← Structure of a database · All IGCSE Computer Science lessons · Practice IGCSE Computer Science questions (free, instant scoring) · The six logic gates →