Concept Explanation
A plain SELECT * FROM orders hands you rows. Real applications need answers: "how much has each customer spent?", "which products have never sold?", "who are our five most active reviewers?" Those answers span multiple tables.
The tempting beginner move is to pull every row into Python and loop over it. Resist that. The database engine is decades-old C code tuned for exactly this work — a query it answers in 3 milliseconds can take a Python loop 30 seconds, because every single row has to cross the process boundary and become a Python object.
Aggregate Functions
An aggregate collapses many rows into a single value.
| Function | Answers |
|---|---|
COUNT(*) | How many rows? |
SUM(col) | What is the total? |
AVG(col) | What is the average? |
MIN(col) / MAX(col) | What are the extremes? |
GROUP BY: One Answer Per Bucket
GROUP BY sorts rows into buckets first, then aggregates each bucket on its own.
SELECT department, COUNT(*), AVG(salary)
FROM employees
GROUP BY department;
You get one row per department instead of one row overall.
WHERE vs HAVING
This distinction trips up almost everyone:
WHEREfilters individual rows before grouping.HAVINGfilters whole groups after aggregation.
"Only permanent staff" is a WHERE. "Only departments averaging over 50,000" is a HAVING.
JOIN: Stitching Tables Together
| Join type | Keeps |
|---|---|
INNER JOIN | Only rows with a match on both sides |
LEFT JOIN | Every left row; NULL where the right side has no match |
LEFT JOIN ... WHERE right.id IS NULL is the standard way to ask "which rows have no match?" — the "products that never sold" question.
Code Example #1 (Basic)
Grouping and aggregating in a single round trip.
import sqlite3
with sqlite3.connect(":memory:") as db:
cur = db.cursor()
cur.execute("CREATE TABLE sales (region TEXT, amount REAL)")
cur.executemany(
"INSERT INTO sales VALUES (?, ?)",
[("North", 100.0), ("North", 250.0), ("South", 75.0), ("East", 500.0)],
)
cur.execute("""
SELECT region, COUNT(*) AS n, SUM(amount) AS total
FROM sales
GROUP BY region
HAVING SUM(amount) > 90
ORDER BY total DESC
""")
for region, n, total in cur.fetchall():
print(f"{region:<6} {n} sale(s) ${total:,.2f}")
Output:
East 1 sale(s) $500.00
North 2 sale(s) $350.00
South never appears: the HAVING clause drops it because its group total is only 75.
Code Example #2 (Intermediate)
A LEFT JOIN that finds the gaps.
import sqlite3
db = sqlite3.connect(":memory:")
db.row_factory = sqlite3.Row # rows now behave like dictionaries
cur = db.cursor()
cur.executescript("""
CREATE TABLE authors (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE books (id INTEGER PRIMARY KEY, author_id INTEGER, title TEXT);
INSERT INTO authors (name) VALUES ('Ada'), ('Grace'), ('Alan');
INSERT INTO books (author_id, title) VALUES (1, 'Notes'), (1, 'Engines'), (2, 'COBOL');
""")
# Who has written nothing at all?
cur.execute("""
SELECT a.name
FROM authors AS a
LEFT JOIN books AS b ON b.author_id = a.id
WHERE b.id IS NULL
""")
print("Silent authors:", [row["name"] for row in cur.fetchall()])
# How many books each -- including the zeroes
cur.execute("""
SELECT a.name, COUNT(b.id) AS book_count
FROM authors AS a
LEFT JOIN books AS b ON b.author_id = a.id
GROUP BY a.id
ORDER BY book_count DESC
""")
for row in cur.fetchall():
print(row["name"], "->", row["book_count"])
db.close()
Note COUNT(b.id) rather than COUNT(*). Counting the joined column returns 0 for Alan, whereas COUNT(*) would count his single all-NULL padding row and wrongly report 1.
Common Mistakes
- Selecting an ungrouped column:
SELECT name, department FROM employees GROUP BY department— which name? SQLite quietly picks an arbitrary one; PostgreSQL raises an error. Only select columns you grouped by or aggregated. - Using WHERE for an aggregate:
WHERE SUM(amount) > 90fails, because the sum does not exist yet at row-filtering time. That belongs inHAVING. - Reaching for
COUNT(*)on a LEFT JOIN: it can never return 0, because the padding row still counts. Count the joined table's key column instead. - Forgetting the ON clause:
SELECT * FROM authors, booksis a cross join — every author paired with every book. Three authors and three books silently become nine rows. - String-formatting user input into SQL:
f"WHERE name = '{name}'"is a SQL-injection hole. Always pass?placeholders plus a parameter tuple and let the driver quote for you.
Best Practices
- Alias your tables:
FROM authors AS akeeps long joins readable and makes ambiguous column names impossible. - Set
row_factory = sqlite3.Row: readingrow["name"]instead ofrow[0]survives someone adding a column to the SELECT list. - Name your aggregates:
COUNT(*) AS book_countgives you a readable key and a stable column name across drivers. - Measure before optimising: prefix a slow query with
EXPLAIN QUERY PLAN(SQLite) orEXPLAIN ANALYZE(PostgreSQL). A missing index on the join column is the usual culprit. - Index your foreign keys:
CREATE INDEX idx_books_author ON books(author_id)turns a full table scan into a direct lookup.
Practice Exercises
- The Sales Report: Build
orders(customer TEXT, product TEXT, amount REAL), insert a dozen rows, then print one line per customer showing their order count and total spend, highest spender first. - The Dormant Accounts: Create
usersandloginstables and use aLEFT JOINto list every user who has never logged in. - The Threshold Filter: Extend exercise 1 so only customers with more than two orders appear — and add a comment explaining why that filter has to be
HAVINGand notWHERE.