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

8.3.2 Selecting, Filtering and Sorting Data

🔒 Lesson slides are available to signed-in users. Sign in

8.3.2 Selecting, Filtering and Sorting Data

Once tables contain data, a query can retrieve only the information needed for a particular task. In this section, you will build one-table SQL queries using SELECT, FROM, WHERE and ORDER BY.

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

  • Explain how a SELECT query retrieves data without changing the source table.
  • Write one-table queries using SELECT ... FROM.
  • Choose specific output attributes or use * when every attribute is required.
  • Use WHERE with suitable comparison operators and correctly written values.
  • Combine conditions using AND or OR.
  • Sort query output with ORDER BY, including ascending and descending order.
  • Trace how filtering and sorting change a result set.
  • Find and correct common errors in simple SQL queries.
Scope note: This lesson uses one table at a time. GROUP BY, aggregate functions and two-table queries are covered in 8.3.3. Inserting, updating and deleting data are covered in 8.3.4.

The Example Table

The examples continue the independently created EcoTrack database from Section 8.3.1. The Sensor table contains one tuple for each monitoring sensor.

SensorID SensorType InstalledOn DailyCheckTime SampleInterval
S-104 Air quality 2026-02-14 07:30 10
S-218 Soil moisture 2025-09-03 06:45 30
S-311 Air quality 2026-01-27 08:00 15
S-405 Water level 2024-11-19 05:50 5
S-522 Temperature 2025-06-08 09:15 20
S-607 Air quality 2024-04-22 07:10 60
Result set: the temporary table of rows and columns returned by a query. Running a SELECT query does not alter the tuples in the source table.

Anatomy of a Simple Query

SELECT SensorID, SensorType
FROM Sensor;
SELECT Which attributes should appear?

SensorID, SensorType

FROM Which table supplies the data?

Sensor

; Where does the statement end?

After the final clause

The attributes after SELECT become the result columns. The table after FROM supplies the candidate tuples.

Exam tip: Read the request in two parts: “What must be displayed?” gives the SELECT list, and “Where is it stored?” gives the FROM table.

Selecting the Required Columns

More than one attribute can be selected. Attribute names are separated by commas and are not enclosed in parentheses.

SELECT SensorID, InstalledOn, SampleInterval
FROM Sensor;

Use * only when every attribute is required:

SELECT *
FROM Sensor;
Request Suitable SELECT list Reason
Show sensor identifiers and types. SensorID, SensorType Only the two requested attributes are returned.
Show the complete Sensor table. * Every attribute is required.
Show installation dates only. InstalledOn A single output column is enough.
Common mistake: SELECT * does not mean “select every tuple.” It means “include every attribute.” Tuple filtering is controlled by WHERE.

Filtering Tuples with WHERE

A WHERE clause keeps only tuples for which its condition is true.

SELECT SensorID, SensorType
FROM Sensor
WHERE SensorType = 'Air quality';

The output contains three tuples because three sensors have the stored type 'Air quality'.

SensorID SensorType
S-104Air quality
S-311Air quality
S-607Air quality

Writing values correctly

Kind of value Example condition Writing rule
Text SensorType = 'Water level' Place the text value in quotation marks.
Number SampleInterval <= 20 Do not place an ordinary numeric value in quotation marks.
Date InstalledOn >= '2025-01-01' Use a valid SQL date representation, normally quoted in written examples.
Time DailyCheckTime < '08:00' Use a valid time representation, normally quoted in written examples.
Boolean Active = TRUE Use the Boolean value expected by the DBMS.
Common mistake: Quotation marks surround a literal value such as 'Air quality'. They should not surround an attribute name such as SensorType.

Comparison Operators

The operator in a WHERE condition determines how an attribute value is compared with another value.

Operator Meaning Example
= Equal to SensorType = 'Temperature'
<> Not equal to SensorType <> 'Air quality'
< Less than SampleInterval < 15
<= Less than or equal to SampleInterval <= 20
> Greater than SampleInterval > 30
>= Greater than or equal to InstalledOn >= '2025-01-01'
Exam tip: Pay close attention to inclusive language. “At least 20” means >= 20, while “more than 20” means > 20.

Combining Conditions

Use AND when every condition must be true. Use OR when at least one of the conditions may be true.

AND: both tests must pass

SELECT SensorID, SensorType, SampleInterval
FROM Sensor
WHERE SensorType = 'Air quality'
AND SampleInterval <= 15;

Only S-104 and S-311 satisfy both conditions.

OR: either test may pass

SELECT SensorID, SensorType
FROM Sensor
WHERE SensorType = 'Water level'
OR SensorType = 'Temperature';

This returns S-405 and S-522.

Common mistake: AND makes a filter more restrictive because a tuple must pass every condition. OR usually allows more tuples through.

Sorting Query Output with ORDER BY

ORDER BY arranges the result set. It does not permanently reorder the tuples stored in the source table.

SELECT SensorID, SensorType, SampleInterval
FROM Sensor
ORDER BY SampleInterval;

Ascending order is the usual default. It may also be written explicitly:

SELECT SensorID, SensorType, SampleInterval
FROM Sensor
ORDER BY SampleInterval ASC;

Use DESC for descending order:

SELECT SensorID, SensorType, SampleInterval
FROM Sensor
ORDER BY SampleInterval DESC;
Data ASC DESC
Numbers Smallest to largest Largest to smallest
Text A to Z Z to A
Dates Earliest to latest Latest to earliest
Times Earlier to later Later to earlier

Sorting by more than one attribute

SELECT SensorID, SensorType, SampleInterval
FROM Sensor
ORDER BY SensorType ASC, SampleInterval DESC;

The first attribute is the main sort key. The second resolves ties between tuples that have the same first value.

Exam tip: Write ORDER BY after WHERE. It sorts the tuples that remain after filtering.

How the Clauses Shape the Result

SQL is written in one order, but it is helpful to imagine the DBMS building the result in the following logical sequence:

1

FROM

Start with tuples from the named table.

2

WHERE

Keep only tuples whose condition is true.

3

SELECT

Keep only the requested output attributes.

4

ORDER BY

Arrange the final result set.

Written clause order: SELECT → FROM → WHERE → ORDER BY
Useful logical model: FROM → WHERE → SELECT → ORDER BY

Worked Example: Build a Query from a Request

Display the sensor identifier, type and sampling interval for sensors sampled every 20 minutes or less. Put the slowest qualifying interval first.

Step 1: Identify the output attributes

The requested columns are SensorID, SensorType and SampleInterval.

Step 2: Identify the source table

All three attributes are stored in Sensor.

Step 3: Translate the filter

“20 minutes or less” becomes SampleInterval <= 20.

Step 4: Translate the required order

“Slowest qualifying interval first” means the largest value must appear first, so use DESC.

SELECT SensorID, SensorType, SampleInterval
FROM Sensor
WHERE SampleInterval <= 20
ORDER BY SampleInterval DESC;

Result

SensorID SensorType SampleInterval
S-522Temperature20
S-311Air quality15
S-104Air quality10
S-405Water level5
Exam tip: Translate the request phrase by phrase: output → table → condition → order.

Interactive: SELECT Query Explorer

Build queries from controls, trace a query clause by clause and diagnose common errors.

Build and run a one-table query

Output attributes
-- Build a query
Choose columns, an optional filter and an optional sort.
Result
No query has been run.

Common Mistakes and Misconceptions

  • Using parentheses around the SELECT attribute list.
  • Forgetting commas between selected attributes.
  • Writing SELECT * when only a few attributes are requested.
  • Forgetting quotation marks around text, date or time literal values.
  • Putting quotation marks around an attribute name.
  • Using AND when the request means that either condition may be true.
  • Confusing “at least” with “greater than.”
  • Writing ORDER BY before WHERE.
  • Assuming ORDER BY permanently changes the source table.
  • Forgetting that ascending order is the usual default.
  • Including GROUP BY or a join when the question needs only one-table filtering.

Practice

Original practice tasks

A community library stores the following table:

Book(BookID, Title, Genre, PublishedYear, LoanPeriod, Available)

  1. Write a query to display every attribute from Book.
  2. Display only Title and Genre.
  3. Display books whose genre is 'History'.
  4. Display books published in or after 2020.
  5. Display books with a loan period of less than 21 days.
  6. Display available history books.
  7. Display books that are either Science or Technology.
  8. Display titles in alphabetical order.
  9. Display the newest books first.
  10. Display Title, Genre and PublishedYear for books published in or after 2018, with the newest year first.
  11. Explain why the following query is incorrect and rewrite it:
    SELECT Title Genre
    FROM Book
    ORDER BY PublishedYear DESC
    WHERE Available = TRUE;

Review

Clause Purpose Position in the written query
SELECT Chooses output attributes. First
FROM Names the source table. After SELECT
WHERE Filters tuples using a condition. After FROM
ORDER BY Sorts the result set. After WHERE, when WHERE is present
ASC Sorts in ascending order. After the sort attribute
DESC Sorts in descending order. After the sort attribute
Final exam tip: Build a one-table query in four decisions: output attributes → source table → optional condition → optional order.