The power of SQL lies in summarizing data and combining tables without writing loops in Python.
Aggregate functions
They compute a single value from many rows: COUNT (how many), SUM (sum), AVG (average), MIN and MAX.
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE sales (category TEXT, amount INTEGER)")
con.executemany("INSERT INTO sales VALUES (?, ?)", [
("fruit", 10), ("meat", 25), ("fruit", 5), ("drinks", 7), ("meat", 3),
])
print(con.execute("SELECT COUNT(*), SUM(amount), AVG(amount), MIN(amount), MAX(amount) FROM sales").fetchone())
# (5, 50, 10.0, 3, 25)
GROUP BY: one result per group
GROUP BY forms one group for each distinct value of a column and computes the aggregates inside each group.
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE sales (category TEXT, amount INTEGER)")
con.executemany("INSERT INTO sales VALUES (?, ?)", [
("fruit", 10), ("meat", 25), ("fruit", 5), ("drinks", 7), ("meat", 3),
])
query = """
SELECT category, SUM(amount), COUNT(*)
FROM sales
GROUP BY category
ORDER BY SUM(amount) DESC, category
"""
for category, total, k in con.execute(query):
print(f"{category}: {total} (sales: {k})")
# meat: 28 (sales: 2)
# fruit: 15 (sales: 2)
# drinks: 7 (sales: 1)
You apply it in Total per category.
HAVING: filtering groups
WHERE filters rows before grouping; HAVING filters groups after computing the aggregates.
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE grades (subject TEXT, grade INTEGER)")
con.executemany("INSERT INTO grades VALUES (?, ?)", [
("maths", 8), ("language", 5), ("maths", 6), ("physics", 9), ("language", 7),
])
query = """
SELECT subject, AVG(grade), COUNT(*)
FROM grades
GROUP BY subject
HAVING COUNT(*) >= 2
ORDER BY subject
"""
print(con.execute(query).fetchall())
# [('language', 6.0, 2), ('maths', 7.0, 2)]
"physics" has a single grade and is left out. Practise with Statistics per subject.
Relating tables: keys and JOIN
Instead of repeating the customer's name in every order, it is stored in its own table and the orders reference it by its id. To join them again, JOIN is used.
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT)")
con.execute("CREATE TABLE orders (customer_id INTEGER, amount INTEGER)")
con.executemany("INSERT INTO customers (name) VALUES (?)", [("ana",), ("bea",), ("carlos",)])
con.executemany("INSERT INTO orders VALUES (?, ?)", [(1, 10), (1, 20), (3, 5)])
query = """
SELECT c.name, o.amount
FROM customers c JOIN orders o ON o.customer_id = c.id
ORDER BY c.name, o.amount
"""
print(con.execute(query).fetchall())
# [('ana', 10), ('ana', 20), ('carlos', 5)]
c and o are aliases (short names) for the tables, and ON states which columns must match. JOIN only returns the rows that have a partner: "bea", with no orders, does not appear.
LEFT JOIN: keeping rows without a partner
LEFT JOIN keeps all the rows of the left table; if there is no partner, the columns of the right one are NULL (None). COALESCE(x, 0) replaces NULL with 0.
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT)")
con.execute("CREATE TABLE orders (customer_id INTEGER, amount INTEGER)")
con.executemany("INSERT INTO customers (name) VALUES (?)", [("ana",), ("bea",), ("carlos",)])
con.executemany("INSERT INTO orders VALUES (?, ?)", [(1, 10), (1, 20), (3, 5)])
query = """
SELECT c.name, COALESCE(SUM(o.amount), 0), COUNT(o.amount)
FROM customers c LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id
ORDER BY c.name
"""
for name, total, k in con.execute(query):
print(f"{name}: {total} (orders: {k})")
# ana: 30 (orders: 2)
# bea: 0 (orders: 0)
# carlos: 5 (orders: 1)
Note that COUNT(o.amount) is counted and not COUNT(*): that way customers without orders give 0. It is the exercise Customers and orders.
Good practices and next steps
- Always use
?parameters for values. - Write a complete
ORDER BYwhen the order matters. - Group related operations in a transaction (
with con:). - Declare constraints (
PRIMARY KEY,NOT NULL,CHECK,UNIQUE) to protect the data. - Close the connection (
con.close()) when you finish with a file. - For large files, indexes (
CREATE INDEX) speed up searches. - For large applications there are other engines (PostgreSQL, MySQL) with very similar usage.