The web and SQL databases · Part 21 of 36
SQL: asking questions of your data
Intermediate 18 min
Tables, keys and relationships, SELECT with WHERE, ORDER BY and GROUP BY, JOINs, and safe parameterised queries.
What you will learn
- You can design small tables with primary and foreign keys.
- You can write SELECT queries with filters, sorting, grouping and joins.
- You can protect queries against SQL injection with parameters.
Before this: HTTP: how browsers and servers talk
Relational databases
A relational database stores data in tables: rows (records) and columns (fields), each column with a type. SQL (Structured Query Language) describes what you want; the database figures out how to get it fast. SQLite (a file-based database built into Python and many apps), PostgreSQL and MySQL are the common ones.
CREATE TABLE beds (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL UNIQUE,
area_m2 REAL NOT NULL CHECK (area_m2 > 0)
);
CREATE TABLE harvests (
id INTEGER PRIMARY KEY,
bed_id INTEGER NOT NULL REFERENCES beds(id),
crop TEXT NOT NULL,
kg REAL NOT NULL,
day TEXT NOT NULL -- ISO date '2026-08-14'
);
The primary key identifies each row. A foreign key (bed_id) points to a row in another table — that is the "relation". Instead of repeating the bed's name in every harvest, you store it once (normalisation).

Reading data
SELECT crop, kg, day
FROM harvests
WHERE kg >= 1 AND day >= '2026-06-01'
ORDER BY kg DESC
LIMIT 10;
Clauses run logically in this order: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT.
Grouping
SELECT crop, COUNT(*) AS picks, SUM(kg) AS total_kg
FROM harvests
GROUP BY crop
HAVING SUM(kg) > 5
ORDER BY total_kg DESC;
GROUP BY collapses rows into one per group; aggregate functions (COUNT, SUM, AVG, MIN, MAX) summarise each group. WHERE filters rows before grouping, HAVING filters groups after.
Joining tables
SELECT b.name, SUM(h.kg) AS total_kg
FROM beds AS b
LEFT JOIN harvests AS h ON h.bed_id = b.id
GROUP BY b.name;
An inner JOIN keeps only rows with a match on both sides; a LEFT JOIN keeps every bed, even those without harvests (their SUM is NULL). NULL means "unknown": NULL = NULL is not true; test with IS NULL.
Changing data
INSERT INTO beds (name, area_m2) VALUES ('north', 3.6);
UPDATE beds SET area_m2 = 4.2 WHERE name = 'north';
DELETE FROM harvests WHERE day < '2020-01-01';
Forgetting the WHERE in an UPDATE or DELETE changes every row. Wrap related changes in a transaction (BEGIN … COMMIT): all of them happen, or none.
Never build SQL from user input
# WRONG — SQL injection: name = "x'; DROP TABLE beds; --"
cur.execute(f"SELECT * FROM beds WHERE name = '{name}'")
# RIGHT — parameterised query
cur.execute("SELECT * FROM beds WHERE name = ?", (name,))
// node:sqlite (Node.js 22.5+) or any driver: placeholders, never string concatenation
db.prepare("SELECT * FROM beds WHERE name = ?").get(name);
With parameters, the database treats the input strictly as a value, never as SQL. Injection is still in the OWASP Top 10:2025 (A05) — and it is completely avoidable.
Indexes
An index is a sorted structure (usually a B-tree) on one or more columns. It turns lookups from O(n) scans into O(log n) searches — at the cost of storage and slower writes. Add them for columns you filter or join on; EXPLAIN QUERY PLAN (SQLite) or EXPLAIN (PostgreSQL) shows whether they are used.
Key points
- Tables have rows and typed columns; primary keys identify rows, foreign keys relate tables.
- SELECT … FROM … WHERE … GROUP BY … HAVING … ORDER BY … LIMIT.
- WHERE filters rows before grouping; HAVING filters groups after.
- INNER JOIN keeps matches; LEFT JOIN keeps all left rows. NULL needs IS NULL.
- Always use parameterised queries; use transactions and indexes wisely.
Flashcards
- Question: What is a foreign key?
- Answer: A column that refers to the primary key of another table.
- Question: What is the difference between WHERE and HAVING?
- Answer: WHERE filters rows before grouping; HAVING filters groups after aggregation.
- Question: What does a LEFT JOIN keep?
- Answer: Every row of the left table, with NULLs where the right side has no match.
- Question: How do you prevent SQL injection?
- Answer: Use parameterised queries (placeholders) instead of building SQL strings.
Check yourself
Think about your answer, then open it. In the app the quiz is interactive, earns points and brings back what you missed.
Order the logical processing of these SQL clauses.
Show the answer
FROM → WHERE → GROUP BY → HAVING → ORDER BY
Rows are fetched, filtered, grouped, groups filtered, then sorted.
Source: PostgreSQL docs, 7.2 Table Expressions
Which query is safe against SQL injection?
- cur.execute("SELECT * FROM beds WHERE name = ?", (name,))
- cur.execute("SELECT * FROM beds WHERE name = '" + name + "'")
- cur.execute(f"SELECT * FROM beds WHERE name = '{name}'")
- cur.execute("SELECT * FROM beds WHERE name = %s" % name)
Show the answer
cur.execute("SELECT * FROM beds WHERE name = ?", (name,))
Only the placeholder version sends the value separately from the SQL text.
Source: OWASP SQL Injection Prevention Cheat Sheet
Three beds exist; only two have harvests. How many rows does the LEFT JOIN … GROUP BY b.name query return?
- 3
- 2
- 0
- 6
Show the answer
3
LEFT JOIN keeps every bed, so all three appear (one with NULL total).
Source: SQLite docs, SELECT
To test whether a column has no value you write WHERE kg IS ___.
Show the answer
NULL
NULL = NULL is not true; use IS NULL.
Source: SQLite docs, NULL handling
Which statements about indexes are true?
- They speed up lookups on the indexed columns
- They make every write faster
- They need extra storage
- EXPLAIN shows whether a query uses them
Show the answer
They speed up lookups on the indexed columns; They need extra storage; EXPLAIN shows whether a query uses them
Indexes speed up reads but cost space and slow writes slightly.
Source: PostgreSQL docs, ch. 11 Indexes
Sources
- SQLite documentation: SQL As Understood By SQLite, SQLite, 2025
- PostgreSQL 18 Documentation: The SQL Language, PostgreSQL Global Development Group, 2025
- OWASP SQL Injection Prevention Cheat Sheet, OWASP, 2025
Facts checked on 2026-11-30. Skillgrove lessons are free learning material — no certificate and no accreditation.