Edexcel International Advanced Level Computer Science, point 8.3.4
To filter and refine data means to retrieve only the rows you want, in the order you want, and summarised as you want. Doing this in the SQL query is more efficient than fetching everything and filtering in Python. (Check the PLS for the exact features allowed.)
The examples use the Player table (PlayerID, Name, Team, Goals) from 8.3.3, with one more player whose goals haven't been recorded:
| PlayerID | Name | Team | Goals |
|---|---|---|---|
| 1 | Mia | Reds | 4 |
| 2 | Leo | Blues | 7 |
| 3 | Ava | Reds | 2 |
| 4 | Kai | Blues | 5 |
| 5 | Sol | Reds | NULL |
Filtering rows: WHERE
SELECT Name FROM Player WHERE Goals >= 5; -- Leo, Kai
SELECT Name FROM Player WHERE Team = 'Reds' AND Goals > 3; -- Mia
-- Mia, Leo, Kai
SELECT Name FROM Player WHERE Team = 'Blues' OR Goals > 3;
SELECT Name FROM Player WHERE NOT Team = 'Reds'; -- Leo, Kai
- Comparison operators:
=(one equals sign in SQL),<>or!=,<,>,<=,>=. - Combine with
AND,OR,NOT, using brackets for clarity. - Text values need quotes, and numbers don't.
More ways to filter
| Feature | Example | Meaning |
|---|---|---|
BETWEEN |
Goals BETWEEN 2 AND 5 |
2 to 5 inclusive |
IN |
Team IN ('Reds', 'Greens') |
One of a list |
LIKE |
Name LIKE 'K%' |
Pattern: % is any characters, _ is one character |
IS NULL |
Goals IS NULL |
No value recorded |
IS NOT NULL |
Goals IS NOT NULL |
Has a value |
SELECT Name FROM Player WHERE Name LIKE 'K%'; -- Kai
-- Leo (2nd letter e)
SELECT Name FROM Player WHERE Name LIKE '_e%';
SELECT Name FROM Player WHERE Goals IS NULL; -- Sol
= NULL doesn't work: use IS NULL. NULL isn't equal to anything, not even to NULL.
Sorting: ORDER BY
-- ascending (default)
SELECT Name, Goals FROM Player ORDER BY Goals;
SELECT Name, Goals FROM Player ORDER BY Goals DESC; -- descending
SELECT Name, Team, Goals FROM Player
-- by team, then goals
ORDER BY Team ASC, Goals DESC;
Limiting: LIMIT
SELECT Name, Goals FROM Player
WHERE Goals IS NOT NULL
ORDER BY Goals DESC
-- the top two: Leo, Kai
LIMIT 2;
Removing duplicates: DISTINCT
SELECT DISTINCT Team FROM Player; -- Reds, Blues
Summarising: aggregates, GROUP BY and HAVING
SELECT COUNT(*) FROM Player; -- 5
-- 4.5 (NULL ignored)
SELECT AVG(Goals) FROM Player;
SELECT Team, COUNT(*), AVG(Goals)
FROM Player
-- one row per team
GROUP BY Team;
| Team | COUNT(*) | AVG(Goals) |
|---|---|---|
| Blues | 2 | 6.0 |
| Reds | 3 | 3.0 |
GROUP BYmakes one row per group, and aggregates apply to each group.HAVINGfilters the groups (after grouping), butWHEREfilters rows before grouping:
SELECT Team, AVG(Goals) FROM Player
GROUP BY Team
HAVING AVG(Goals) > 4; -- only Blues
The order of clauses
SELECT ... FROM ... [JOIN ...] WHERE ...
GROUP BY ... HAVING ... ORDER BY ... LIMIT ...
Running refined queries from Python
With placeholders for any user values:
import sqlite3
conn = sqlite3.connect("club.db")
cur = conn.cursor()
min_goals = 3
cur.execute("""SELECT Name, Goals FROM Player
WHERE Goals >= ? AND Team = ?
ORDER BY Goals DESC""", (min_goals, "Reds"))
for name, goals in cur.fetchall():
print(name, goals) # Mia 4
pattern = "K%"
cur.execute("SELECT Name FROM Player WHERE Name LIKE ?", (pattern,))
print(cur.fetchall()) # [('Kai',)]
Placeholders work for values only, not for table or column names.
Doing the filtering in the SQL query means the database does the work (often using indexes), and only the wanted rows travel to Python, which is faster and uses less memory for large tables.
Worked example
Task: write a query for the names and goals of Reds players with at least 2 goals, best first, then another for the number of players in each team whose average is above 2.
SELECT Name, Goals
FROM Player
WHERE Team = 'Reds' AND Goals >= 2
ORDER BY Goals DESC;
Result: Mia 4, Ava 2.
SELECT Team, COUNT(*) AS Players
FROM Player
GROUP BY Team
HAVING AVG(Goals) > 2;
Result: Blues | 2 (average 6.0) and Reds | 3 (average 3.0). Sol's NULL goals are ignored by AVG, but Sol is still counted by COUNT(*).
Exam tip: know the order of clauses, and the difference between WHERE (filters rows) and HAVING (filters groups). Use IS NULL, not = NULL. LIKE uses % for "any characters". Use placeholders for values from the user.
Check yourself
What is the difference between WHERE and HAVING?
WHERE filters individual rows before grouping. HAVING filters the groups after GROUP BY, usually using an aggregate.
Which pattern finds names ending in a?
Name LIKE '%a'.
How do you find rows where Goals has no value?
WHERE Goals IS NULL (not = NULL).
Which clause sorts the results from highest to lowest?
ORDER BY with DESC, for example ORDER BY Goals DESC.
What does DISTINCT do?
It removes duplicate rows from the result, so each value (such as each team name) appears only once.