SQL queries: SELECT, WHERE, ORDER BY, SUM and COUNT
The syllabus asks you to read and write SQL that queries one table. There are only a few keywords, but marks go on exact details: the right fields, the right order, and conditions that pick exactly the right rows.
The shape of a query
SELECT lists the fields to show, FROM names the table, WHERE gives the condition rows must meet, and ORDER BY sorts the result. ASC (the default) sorts smallest or earliest first, and DESC the other way.
SELECT Title, Price
FROM BOOK
WHERE Price < 10 AND InStock = TRUE
ORDER BY Price DESC;Conditions
WHERE uses the comparisons =, <>, <, >, <= and >=, joined with AND (both parts must be true) or OR (either part). Text values go in quotes, such as Genre = 'Horror'. Numbers and Boolean values don’t.
SUM and COUNT
SUM adds up the values in a numeric field, and COUNT counts the rows. Both can be combined with WHERE to work on only some rows.
SELECT SUM(Distance)
FROM RIDE
WHERE BikeType = 'Electric';
SELECT COUNT(*)
FROM RIDE
WHERE Distance > 5;Reading a query
When asked what a query outputs, go through the table row by row and keep only the rows that meet the WHERE condition. Show only the fields in SELECT, in the order they are listed, then sort by the ORDER BY field.
Where marks go
- Showing extra fields, or leaving one out: SELECT must list exactly what the question asks for.
- Using OR where the question means AND.
- Forgetting quotes around text values, or putting them around numbers.
- Sorting the wrong way: “highest first” needs DESC.
- Getting the table name wrong in FROM.
Try a question
3 MARKS · MARKED ON THIS PAGEA school library stores details of its books in the table BOOK, shown above. Write an SQL query to display only the Title and Author of every book with the Genre Mystery.
BOOK
| BookID | Title | Author | Genre | Pages |
|---|---|---|---|---|
| B001 | The Silent Harbour | Mira Patel | Mystery | 312 |
| B002 | Rockets for Beginners | Tom Okafor | Science | 198 |
| B003 | Midnight at Elm Lane | Sara Lindqvist | Mystery | 276 |
| B004 | The Last Orchard | Jonah Reyes | Adventure | 340 |
| B005 | Clues in the Snow | Mira Patel | Mystery | 254 |
| B006 | Deep Ocean Life | Hana Sato | Science | 221 |
| B007 | Island of Echoes | Jonah Reyes | Adventure | 405 |
| B008 | The Missing Key | Leo Brandt | Mystery | 189 |