SYLLABUS 9.4 · PAPER 2 · ALSO FOR 0984 AND 2210

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 PAGE

A 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

BookIDTitleAuthorGenrePages
B001The Silent HarbourMira PatelMystery312
B002Rockets for BeginnersTom OkaforScience198
B003Midnight at Elm LaneSara LindqvistMystery276
B004The Last OrchardJonah ReyesAdventure340
B005Clues in the SnowMira PatelMystery254
B006Deep Ocean LifeHana SatoScience221
B007Island of EchoesJonah ReyesAdventure405
B008The Missing KeyLeo BrandtMystery189
Fill in your answer first.