Querying with SQL
Querying with SQL
- SQL (Structured Query Language) picks out the records you want.
- A few keywords do almost everything at IGCSE.
- Read a query in a fixed order to work out its output.
SELECT, FROM, WHERE
SELECT FirstName, FormClass
FROM Student
WHERE FeesPaid = TRUE;
SELECT= which fields to show (use*for all).FROM= which table.WHERE= a condition, so only matching records appear.
Practice
In an SQL query, SELECT specifies:
SELECT chooses the fields; FROM the table; WHERE the rows; ORDER BY the sort.
Practice
The WHERE clause:
WHERE filters rows by a condition.
ORDER BY, AND, OR
SELECT FirstName, DateOfBirth
FROM Student
WHERE FormClass = '10A' AND FeesPaid = FALSE
ORDER BY DateOfBirth ASC;
ORDER BYsorts:ASC(smallest/A→Z first) orDESC(largest/Z→A first).- Join conditions with
AND(both true) orOR(at least one true).
Practice
ORDER BY mark DESC sorts the results:
DESC = descending (largest/Z→A first); ASC = ascending.
SUM, COUNT, and reading order
COUNTcounts matching records;SUMadds up a number field.- To work out a query's output, read it in this order:
- FROM (which table) → WHERE (keep matching rows) → SELECT (show chosen fields) → ORDER BY (sort).
SELECT COUNT(StudentID) FROM Student WHERE FeesPaid = FALSE;
Practice
What does COUNT(StudentID) return?
COUNT counts rows; SUM would add up a number field instead.
Practice
Put the SQL clauses in the order you read them to find the output.
FROM → WHERE → SELECT → ORDER BY gives you exactly which rows and columns appear.
You've got it
Key idea
SELECT(fields) ·FROM(table) ·WHERE(condition);*= all fieldsORDER BY … ASC/DESCsorts;AND/ORjoin conditionsCOUNTcounts rows;SUMtotals a number field- read a query: FROM → WHERE → SELECT → ORDER BY