A-Level Computer Science / Unit 8: Relational Databases and SQL

8.2.5 SQL DML: SELECT, WHERE and ORDER BY

πŸ”’ Lesson slides are available to signed-in users. Sign in

8.2.5 SQL DML: SELECT, WHERE and ORDER BY

A SELECT query names output fields and a source table. WHERE filters rows; ORDER BY sorts the result.

By the end of this page, you should be able to:

  • define and use the key terms accurately;
  • explain how the idea works using a new example;
  • apply the idea to a database design or SQL task.

1. Build the basic query

SELECT names the fields to display. FROM names the table containing the records. Use an asterisk in SELECT when every field is required. The result is a new set of rows; the source table is not changed.

2. Filter with WHERE

WHERE keeps rows that satisfy a condition. For example, WHERE Zone = 4 selects records with that zone value. Text values are usually placed inside quotation marks. Apply the condition to the field values, not to the output column headings.

3. Sort with ORDER BY

ORDER BY arranges the result by one or more fields. ASC means ascending and DESC means descending. If two records have the same first sort value, a second field can provide a tie-breaker.

4. Separate selection, filtering and sorting

Read a request in parts: what should be displayed, which table contains it, which rows qualify, and what order is needed. These decisions map to SELECT, FROM, WHERE and ORDER BY respectively.

Worked example

For Parcel(ParcelID, Recipient, Zone, DispatchDate), this query lists recipients in zone 4, alphabetically: SELECT Recipient FROM Parcel WHERE Zone = 4 ORDER BY Recipient ASC;

Common mistake to avoid

SELECT * means β€œreturn all fields.” In COUNT(*), the asterisk is used to count rows. The meaning comes from the SQL expression around it.

Interactive check

Choose an answer, read the explanation, and continue to the next example.

Try it

Check your understanding

Question 1 of 3
Score: 0 / 3

Independent practice

Try this original question before opening the suggested response.

Table Trail( TrailID, TrailName, Difficulty, LengthKm). Write a query to show TrailName and LengthKm for trails with difficulty 2, ordered from shortest to longest. (4)

Suggested response
SELECT TrailName, LengthKm
FROM Trail
WHERE Difficulty = 2
ORDER BY LengthKm ASC;

Answering clearly

Use the technical term, state what it does, and connect your explanation to the details in the question.