AQA GCSE Computer Science (8525), section 3.7.2 (Structured query language (SQL))
What is SQL?
SQL (Structured Query Language) is the language used to ask questions of a database, and to add, change and remove data. A question is called a query.
Example tables
Pupil
| PupilID | Name | FormID | Mark |
|---|---|---|---|
| 1 | Aisha | 10A | 72 |
| 2 | Ben | 10B | 45 |
| 3 | Cara | 10A | 88 |
| 4 | Dev | 10B | 61 |
Form
| FormID | Tutor |
|---|---|
| 10A | Ms Patel |
| 10B | Mr Jones |
SELECT ... FROM
SELECT Name, Mark
FROM Pupil;
SELECTsays which fields (columns) to show.*means all fields.FROMsays which table.
WHERE
WHERE filters the records to those that meet a condition.
SELECT Name
FROM Pupil
WHERE Mark >= 60;
Result: Aisha, Cara, Dev.
Conditions can use =, <> (not equal), <, >, <=, >=, and AND, OR. Text is written in quotes.
SELECT Name FROM Pupil WHERE FormID = '10A' AND Mark > 80;
ORDER BY
ORDER BY sorts the results: ASC for ascending (the default) and DESC for descending.
SELECT Name, Mark
FROM Pupil
ORDER BY Mark DESC;
Result: Cara 88, Aisha 72, Dev 61, Ben 45.
Two tables
To use data from two tables, say both tables in FROM and match the keys in WHERE.
SELECT Pupil.Name, Form.Tutor
FROM Pupil, Form
WHERE Pupil.FormID = Form.FormID;
Exam questions use no more than two tables in a query.
Common mistake: forgetting the quotes around text values ('10A'), or leaving out the WHERE that joins two tables (which gives every combination of records). Also, ORDER BY goes after WHERE.
Exam tip: write the query in the order SELECT, FROM, WHERE, ORDER BY, each on its own line. Check field names and use AND or OR for several conditions.
Check yourself
Write a query to show all the fields of every record in the Pupil table.
SELECT * FROM Pupil;
What does ORDER BY Mark DESC do?
It sorts the results from the highest mark to the lowest.
Write a query to show the names of pupils with a mark below 50.
SELECT Name FROM Pupil WHERE Mark < 50;