SQL and relational modeling¶
What you'll be able to do¶
- Turn requirements into related tables with keys and constraints.
- Write SQL that filters, groups, joins, and ranks experiment data without row-by-row Python loops.
- Plan a safe schema change and spot a time-based join that leaks future data.
Start with facts and rules¶
Suppose you track model experiments. A user owns experiments; an experiment has runs; a run has metrics. A spreadsheet per experiment repeats user details, and nothing enforces which run belongs to which experiment across sheets or writers. In a relational database, each table stores one kind of fact as a single source of truth, and keys connect facts. SQL asks what rows you want; the database chooses a way to get them.
Build the model from requirements: identify entities (users, experiments, runs), then relationships. One user can own many experiments, so put user_id in experiments. One experiment can have many runs, so put experiment_id in runs. If a run can have many tags and a tag can label many runs, add run_tags(run_id, tag_id) rather than a comma-separated list. The pair can be its primary key.
Columns have types. A primary key identifies one row; a foreign key points to a parent row. NOT NULL requires a value, UNIQUE prevents duplicate non-null values or combinations, and CHECK enforces a local rule. In SQLite, and by default in PostgreSQL, a nullable UNIQUE column can still hold many NULL entries, so add NOT NULL when a missing value is forbidden. These constraints protect the data even if two different programs write it.
Here is a small SQLite setup. Run the Python block as written. Pass each later SQL statement separately to db.execute(sql) and call .fetchall() to see a query's rows; use db.executescript(sql) for a block containing several statements.
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("PRAGMA foreign_keys = ON")
db.executescript("""
CREATE TABLE users (
id INTEGER PRIMARY KEY, name TEXT NOT NULL
);
CREATE TABLE experiments (
id INTEGER PRIMARY KEY,
owner_id INTEGER NOT NULL REFERENCES users(id),
name TEXT NOT NULL,
UNIQUE(owner_id, name)
);
CREATE TABLE runs (
id INTEGER PRIMARY KEY,
experiment_id INTEGER NOT NULL REFERENCES experiments(id),
started_at INTEGER NOT NULL,
score REAL CHECK(score BETWEEN 0 AND 1)
);
CREATE TABLE metrics (
run_id INTEGER NOT NULL REFERENCES runs(id),
name TEXT NOT NULL,
value REAL NOT NULL,
PRIMARY KEY(run_id, name)
);
INSERT INTO users VALUES (1, 'Ada');
INSERT INTO experiments VALUES (10, 1, 'baseline'), (11, 1, 'new model');
INSERT INTO runs VALUES (101, 10, 100, 0.8), (102, 10, 200, 0.9);
""")
SQLite requires PRAGMA foreign_keys = ON for each connection that should enforce foreign keys. Its type rules are also more permissive than PostgreSQL's: in an ordinary table, a REAL column still accepts text such as 'abc'. When that matters, add CHECK(typeof(value) IN ('integer', 'real')), and test type assumptions again when moving databases. score may be NULL here: CHECK does not imply NOT NULL.
Store each fact once¶
Do not copy the owner's name onto every run. If Ada changes her name, one users row should change, not every experiment and run. This is the practical aim of normalization through third normal form (3NF): a non-key fact belongs to the key of its own table, not to another non-key fact. owner_name depends on owner_id, so it belongs in users. A run's average metric is derived from metric rows; storing both creates a sync problem unless you have a reliable update plan.
An integer id is a surrogate key: stable even if a name changes. A natural key comes from the domain, such as a genuinely stable external identifier. Use a natural key only when its uniqueness and stability are real requirements. You can keep a surrogate primary key and still put UNIQUE(owner_id, name) on the meaningful combination.
Sometimes duplication is intentional. An immutable evaluation snapshot may record the exact prompt or model settings used at run time, even if today's settings differ. A precomputed summary can speed repeated reads, provided you define how it is refreshed. Denormalization trades simpler reads for extra storage and consistency work.
Query sets, then groups¶
Start with rows. WHERE filters, ORDER BY sorts, and LIMIT bounds the result. Include a tie breaker if you need repeatable order.
This returns run 102, then 101. An aggregate collapses rows into groups. WHERE removes individual rows before grouping; HAVING removes groups after aggregation.
SELECT experiment_id, COUNT(*) AS run_count, AVG(score) AS avg_score
FROM runs
WHERE score IS NOT NULL
GROUP BY experiment_id
HAVING COUNT(*) >= 2;
Think in sets, not a Python loop issuing one query per experiment. The useful logical order is FROM (including joins), WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT. Thus WHERE should not rely on a SELECT alias: it does not exist at that stage. PostgreSQL rejects it; SQLite tolerates some non-aggregate aliases, but never an aggregate such as run_count there. Repeat a plain expression in WHERE, put an aggregate condition in HAVING, or filter an outer query. COUNT(*) counts rows; COUNT(score) skips null scores.
Join without inventing rows¶
An inner join keeps only matches. A left join keeps every left row and fills missing right columns with NULL.
To find experiments with no runs, keep all experiments and then select the missing right side:
In the setup, experiment 11 survives. Join on a key with the cardinality you expect. If, for the same join key, two rows on one side match three on the other, that key produces 2 × 3 = 6 rows; an aggregate over that result may silently double or triple count. Inspect row counts before trusting totals.
SQL has three-valued logic: a comparison involving NULL is unknown, and WHERE keeps only true rows. score = NULL never matches, even for a null score. Use IS NULL or IS NOT NULL. A missing joined row and a present row with a null value can look alike, so test a non-null key (r.id) when looking for missing matches.
Compose and rank queries¶
A subquery feeds its result to an outer query. A common table expression, introduced with WITH, names an intermediate result:
WITH counts AS (
SELECT experiment_id, COUNT(*) AS n
FROM runs GROUP BY experiment_id
)
SELECT e.name, counts.n
FROM experiments AS e
JOIN counts ON counts.experiment_id = e.id
WHERE counts.n >= 2;
For a single value, a scalar subquery works too: WHERE score > (SELECT AVG(score) FROM runs). A window function keeps individual rows while calculating across a partition. Here each run gets a rank within its experiment:
SELECT id, experiment_id, score,
ROW_NUMBER() OVER (
PARTITION BY experiment_id ORDER BY score DESC, id
) AS place,
SUM(score) OVER (
PARTITION BY experiment_id ORDER BY started_at, id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_score
FROM runs;
Put this query in a CTE and filter place <= 2 outside it for the top two per experiment. PARTITION BY restarts the count for each experiment; the explicit row frame makes the total advance one ordered row at a time.
Pick the latest eligible row¶
Ranking also answers "what was the newest reading available then?" Here two inline toy tables stand in for real ones:
WITH examples(id, event_time) AS (VALUES (1, 200), (2, 40)),
readings(measured_at, value) AS (VALUES (100, 0.3), (250, 0.9)),
ranked AS (
SELECT e.id, r.value, ROW_NUMBER() OVER (
PARTITION BY e.id ORDER BY r.measured_at DESC
) AS place
FROM examples AS e
LEFT JOIN readings AS r ON r.measured_at <= e.event_time
)
SELECT id, value FROM ranked WHERE place = 1 ORDER BY id;
The result is (1, 0.3) and (2, NULL). The time condition sits in ON, so an example with no eligible reading survives the left join. Real data also needs an entity match in ON, such as the same user, and a tie breaker if two readings can share a time.
Change rows¶
For writes, INSERT adds rows, UPDATE ... WHERE changes selected rows, and DELETE ... WHERE removes selected rows. Check the WHERE before running an update or delete:
INSERT INTO runs VALUES (103, 11, 300, NULL);
UPDATE runs SET score = 0.85 WHERE id = 103;
DELETE FROM runs WHERE id = 103;
Evolve the model and place the work¶
Treat schema changes as versioned code: review and apply each migration once, in order. A common safe sequence is add a nullable column, deploy code that can handle old and new rows, backfill existing rows, then enforce NOT NULL. On SQLite, enforcing some constraints on an existing table requires rebuilding it; PostgreSQL has different migration operations. On a large table, a backfill or constraint change can hold locks or consume enough resources to disrupt writes. Plan the operation and measure it on realistic data.
A SQLite rebuild has four steps: create the new table, copy rows with explicit column names, drop the old table, and rename the new one. Run this toy example with db.executescript(sql):
-- A weak toy table that no other table references.
CREATE TABLE tags (id INTEGER, label TEXT);
INSERT INTO tags (id, label) VALUES (1, 'baseline');
BEGIN;
CREATE TABLE tags_new (
id INTEGER PRIMARY KEY,
label TEXT NOT NULL UNIQUE
);
INSERT INTO tags_new (id, label)
SELECT id, label FROM tags;
DROP TABLE tags;
ALTER TABLE tags_new RENAME TO tags;
COMMIT;
If an old row breaks a new rule, the copy fails; roll back and repair the data. A table that other tables reference needs extra foreign-key steps, so check the SQLite documentation first.
Use SQL to filter and aggregate where the data lives. If a million runs each have ten metrics, pulling all ten million metric rows into pandas just to count runs per experiment transfers far more data than a grouped SQL result. pandas remains useful for flexible local analysis of the selected rows.
For AI engineers¶
For AI engineers
Your training script may append results to CSV files, but experiments, runs, metrics, feature readings, and labels have relationships and update rules. A pile of CSVs cannot enforce those rules. To build a training set, join each example to the feature value available at its event time: require feature_time <= event_time, then choose the latest eligible reading per example. Joining to the latest value overall leaks future information into training. ROW_NUMBER() can also deduplicate repeated examples by keeping one row per example ID under an explicit ordering.
Common mistakes¶
- Using
SELECT *in production code, then breaking when a schema or column order changes. - Joining on non-unique names and multiplying rows without noticing.
- Writing
= NULLor putting a right-table filter inWHEREafter a left join, accidentally dropping unmatched rows. - Storing tags as comma-separated text instead of a join table.
- Omitting foreign keys and checks for assumed speed, then discovering invalid data later.
- Selecting columns that are neither grouped nor aggregated, or building SQL by concatenating user input; pass values as parameters and see Security basics.
Check yourself¶
A user can belong to many teams, and each team can have many users. Where does membership go?
In a join table such as memberships(user_id, team_id), with foreign keys to both tables and a unique or primary key on the pair. A list in either parent row is hard to constrain and query.
An experiment has no runs. Why does an inner join omit it, and what query shape finds it?
An inner join keeps only matched rows. Left join experiments to runs and filter WHERE runs.id IS NULL, testing a non-null key from the right table.
A feature was measured at times 100 and 250; an example occurred at 200. Which value may a point-in-time join use?
The reading at 100. Require measurement time at or before 200, then choose the greatest eligible time. The reading at 250 would leak future information.
Why can WHERE run_count >= 2 fail when run_count is an alias for COUNT(*)?
WHERE runs before grouping and before SELECT creates the alias. Use HAVING COUNT(*) >= 2 or filter a grouped subquery or CTE.
Lab¶
In code/sql-modeling/, write five SQL queries over experiment and feature data. Filter and sort runs; group them; find experiments without runs. Rank runs within experiments and select the most recent eligible feature reading per run. Return SQL statements that rebuild a weak metrics table with useful constraints, including a numeric type check. Run: cd code/sql-modeling && PYTHONPATH=starter python -m pytest tests -q Each passing test represents one completed task; compare results, not SQL spelling.
Go deeper¶
- PostgreSQL documentation for types, joins, and migration behavior beyond SQLite.
- Designed to Scale: SQL vs NoSQL for datastore choice.
- Your Software Engineering Handbook, ch. 7 "CSDL quan hệ (index, query, transaction)".