Relational Databases and SQL
Most business data, customers, orders, payments, bookings, patients, lives in relational databases such as PostgreSQL, MySQL, SQL Server or SQLite. A relational database stores several tables linked by keys, and you ask it questions in SQL. For ML this means two jobs: getting data out with SQL, and turning several linked tables into the single flat table a model needs. The SQL course teaches the language; this lesson shows the ML side with Python's built-in sqlite3 module and an in-memory database.
A small shop database
Data is normalised: each fact is stored once. A customer's country is in customers, not repeated on every order.
import sqlite3
con = sqlite3.connect(":memory:")
con.executescript("""
CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT, country TEXT, signup DATE);
CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER REFERENCES customers(id),
day DATE, amount REAL);
INSERT INTO customers VALUES (1, 'Ana', 'VN', '2026-01-10'), (2, 'Ben', 'DE', '2026-02-03'),
(3, 'Cai', 'VN', '2026-02-20'), (4, 'Dev', 'IN', '2026-03-05');
INSERT INTO orders VALUES (1, 1, '2026-03-01', 25.0), (2, 1, '2026-03-20', 40.0),
(3, 2, '2026-03-02', 15.5), (4, 1, '2026-04-02', 12.0),
(5, 3, '2026-04-10', 80.0), (6, 2, '2026-04-15', 22.0);
""")
for row in con.execute("SELECT * FROM orders WHERE amount > 20 ORDER BY day"):
print(row)
print("customers:", con.execute("SELECT COUNT(*) FROM customers").fetchone()[0])(1, 1, '2026-03-01', 25.0)
(2, 1, '2026-03-20', 40.0)
(5, 3, '2026-04-10', 80.0)
(6, 2, '2026-04-15', 22.0)
customers: 4
From linked tables to one row per customer
Suppose we want to predict something per customer, say whether they will order again. The model needs one row per customer with features summarising their orders. A LEFT JOIN keeps customers without orders, and GROUP BY aggregates:
import sqlite3
import pandas as pd
con = sqlite3.connect(":memory:")
con.executescript("""
CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT, country TEXT, signup DATE);
CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER, day DATE, amount REAL);
INSERT INTO customers VALUES (1, 'Ana', 'VN', '2026-01-10'), (2, 'Ben', 'DE', '2026-02-03'),
(3, 'Cai', 'VN', '2026-02-20'), (4, 'Dev', 'IN', '2026-03-05');
INSERT INTO orders VALUES (1, 1, '2026-03-01', 25.0), (2, 1, '2026-03-20', 40.0),
(3, 2, '2026-03-02', 15.5), (4, 1, '2026-04-02', 12.0),
(5, 3, '2026-04-10', 80.0), (6, 2, '2026-04-15', 22.0);
""")
query = """
SELECT c.id, c.country,
COUNT(o.id) AS n_orders,
COALESCE(SUM(o.amount), 0) AS total_spent,
MAX(o.day) AS last_order
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id AND o.day < :cutoff
GROUP BY c.id
ORDER BY c.id
"""
features = pd.read_sql_query(query, con, params={"cutoff": "2026-04-01"})
print(features) id country n_orders total_spent last_order
0 1 VN 2 65.0 2026-03-20
1 2 DE 1 15.5 2026-03-02
2 3 VN 0 0.0 None
3 4 IN 0 0.0 None
The :cutoff parameter is the important line. Features may only use data from before the moment of prediction; orders on or after 1 April are what the model is supposed to predict, not use. Ana's order of 2 April, Ben's of 15 April and Cai's only order are left out, so Cai and Dev both have zero orders here. Forgetting this filter is the most common way a database query leaks the future into the training data.
Always pass values as parameters (:cutoff, ?) rather than pasting them into the SQL string; it avoids SQL injection and quoting bugs.
Join fan-out
A join repeats rows. If a customer has three orders and two support tickets, joining all three tables gives 3 × 2 = 6 rows for that customer, and any sum over orders is now doubled:
import sqlite3
import pandas as pd
con = sqlite3.connect(":memory:")
con.executescript("""
CREATE TABLE orders (customer_id INTEGER, amount REAL);
CREATE TABLE tickets (customer_id INTEGER, topic TEXT);
INSERT INTO orders VALUES (1, 25.0), (1, 40.0), (1, 12.0);
INSERT INTO tickets VALUES (1, 'late delivery'), (1, 'refund');
""")
wrong = """SELECT o.customer_id, SUM(o.amount) AS spent, COUNT(t.topic) AS tickets
FROM orders o JOIN tickets t ON t.customer_id = o.customer_id GROUP BY o.customer_id"""
right = """SELECT o.customer_id, o.spent, t.tickets
FROM (SELECT customer_id, SUM(amount) AS spent FROM orders GROUP BY customer_id) o
JOIN (SELECT customer_id, COUNT(*) AS tickets FROM tickets GROUP BY customer_id) t
ON t.customer_id = o.customer_id"""
print("joined first: ", pd.read_sql_query(wrong, con).to_dict("records"))
print("aggregated first:", pd.read_sql_query(right, con).to_dict("records"))joined first: [{'customer_id': 1, 'spent': 154.0, 'tickets': 6}]
aggregated first: [{'customer_id': 1, 'spent': 77.0, 'tickets': 2}]
The fix is to aggregate each table to the target grain first (one row per customer), then join. After any join, compare the row count with what you expect.
SQLAlchemy
In real projects you usually connect through SQLAlchemy, which gives one interface to every database: only the connection URL changes (postgresql://…, mysql+pymysql://…, sqlite://). pandas accepts its engine directly:
import pandas as pd
from sqlalchemy import create_engine, text
engine = create_engine("sqlite://") # in-memory SQLite; a server would use its URL
pd.DataFrame({"sensor": ["s1", "s2", "s1"], "value": [3.2, 4.1, 3.5]}).to_sql("readings", engine, index=False)
with engine.connect() as conn:
df = pd.read_sql(text("SELECT sensor, AVG(value) AS mean_value FROM readings GROUP BY sensor"), conn)
print(df) sensor mean_value
0 s1 3.35
1 s2 4.10
Credentials for a real database never belong in code or notebooks: read them from environment variables or a secrets manager, and use an account with read-only rights for analysis.
Pitfalls
- Leaking the future: filter every table by a cutoff time when building features.
- Fan-out: aggregate before joining; check row counts after every join.
NULLsemantics:COUNT(column)skipsNULLs,SUMof no rows isNULL,NULL = NULLis not true. UseCOALESCE.- Querying production: heavy analytical queries can slow down the live system. Use a replica or a data warehouse.
Practice
- Rewrite the feature query so that it also returns each customer's average order amount, with 0 for customers without orders.
Answer
Add COALESCE(AVG(o.amount), 0) AS avg_amount to the SELECT list. AVG over no rows is NULL, which COALESCE turns into 0.
- A table
visitshas one row per hospital visit andlabsone row per lab test (several per visit). You need one row per visit with the number of lab tests and the visit's cost. What is the danger ofSUM(visits.cost)after joining the two?
Answer
Each visit row is repeated once per lab test, so the cost is multiplied by the number of tests. Count the lab tests per visit in a subquery first, then join that one-row-per-visit result to visits.
Test yourself
Why does the feature query filter orders with o.day < :cutoff?
- To make the query faster
- So that features only use information available at prediction time
- Because SQLite cannot sort dates
- To remove duplicate customers
A customer has 3 orders and 2 tickets. Joining orders and tickets on the customer gives how many rows for them?
- 2
- 3
- 5
- 6
Why use LEFT JOIN from customers to orders when building per-customer features?
- It is faster than JOIN
- It keeps customers who have no orders
- It removes NULLs
- It sorts the result