AI from scratch · Stage 4: the engineer's toolkit · Data with SQL
Data with SQL: Extracting and Preparing Training Tables
In real machine learning production, data does not arrive as a tidy, ready-to-fit CSV file. It lives inside transactional relational databases (PostgreSQL, MySQL) and enterprise data warehouses (Snowflake, BigQuery, ClickHouse). Before a model fits a single parameter, a machine learning engineer queries, filters, aggregates, and joins raw event logs using SQL. This lesson covers the SQL habits essential for ML: extracting clean training rows, aggregating historical behavior without leakage, joining metadata safely with LEFT JOIN, and computing point-in-time features with window functions.
1. From raw events to training examples
Supervised machine learning expects a two-dimensional matrix: one row per prediction example, target columns \(y\), and feature columns \(X\). But production databases store transactional events spread across multiple tables. SQL is the language that reshapes those events into an ML dataset:
| SQL Clause | What it does | pandas Equivalent |
|---|---|---|
SELECT col1, col2 | Picks which columns to keep | df[["col1", "col2"]] |
WHERE condition | Filters rows matching criteria | df[df["kind"] == "EL"] |
ORDER BY col DESC | Sorts rows by values | df.sort_values("col", ascending=False) |
LIMIT n | Takes the top n rows | df.head(n) |
You want to train a model to predict whether an escalator outage will take more than 24 hours to repair. Which filter should you place in the WHERE clause?
WHERE kind = 'EL' AND finished = 1WHERE kind = 'ES' AND finished = 1WHERE kind = 'ES'
kind = 'ES'. We must filter for finished = 'True' because ongoing, unfinished outages have unknown true repair durations. Using unfinished outages creates censored data and biases the ground truth label.A training set requires one row per prediction instance; SQL WHERE filters raw event logs down to the exact population of interest.
2. Aggregations: summarizing history with GROUP BY
Raw event rows only show single incidents. To give an ML model predictive signals, we aggregate history: how many times has this specific elevator broken down? How many outages has this station experienced?
GROUP BY collects rows that share a key, and aggregate functions (COUNT, AVG, SUM, MAX, MIN) collapse each group into a single summary row. HAVING filters the aggregated groups, whereas WHERE filters raw rows before grouping:
| station | total_outages |
|---|---|
| Lexington Av/63 St | 24 |
| 42St/Port Authority-Bus Terminal | 18 |
| 61 St-Woodside | 15 |
| Coney Island-Stillwell Av | 14 |
| Grand Central-42 St | 12 |
Select a preset or edit the query above, then click Run SQL.
Predict, then try: what is the fundamental difference between WHERE and HAVING in SQL?
WHEREfilters rows before grouping;HAVINGfilters groups after aggregationWHEREonly works on numbers;HAVINGworks on text- They are completely interchangeable synonyms
WHERE first to discard individual event rows. It then groups remaining rows into buckets (GROUP BY) and computes aggregates. Finally, HAVING discards aggregated buckets whose summary statistics don't match (e.g. HAVING COUNT(*) > 10).GROUP BY condenses historical events into summary features; WHERE filters rows before aggregation, HAVING filters groups after.
3. Joining tables: metadata and feature enrichment
The outages table contains equipment and timestamps, but lacks station-level context: how many lines pass through the station? Is it operated by LIRR or Metro-North? What are its geographic coordinates? To enrich our feature vector, we join the outages table with the stations metadata table:
| Join Type | Behavior | Risk in Machine Learning |
|---|---|---|
LEFT JOIN | Keeps all left rows; fills missing right columns with NULL | Recommended: Preserves all training rows; missing metadata becomes imputable NaNs. |
INNER JOIN | Keeps only rows present in both tables | Dangerous: If a station name has a minor spelling difference, rows are silently dropped! |
Why is an INNER JOIN often dangerous when joining an event table to a metadata lookup table for model training?
- It is significantly slower than LEFT JOIN
- It silently drops training examples whose lookup key is missing or misspelled, introducing selection bias
- It duplicates rows whenever a match is found
INNER JOIN quietly deletes those 5% of training examples. This alters the underlying training distribution and introduces severe selection bias. A LEFT JOIN preserves all training instances.Use LEFT JOIN to enrich training examples; INNER JOIN silently discards examples that fail to match, biasing your training data.
4. Window functions: rolling features without collapsing rows
GROUP BY collapses multiple rows into a single row. But in machine learning, we need every single outage row preserved, augmented with historical context: "At the time this outage started, how many prior outages had this specific piece of equipment suffered?"
Window functions compute aggregations across a partition of rows while preserving each individual row. The syntax is: AGGREGATE() OVER (PARTITION BY key ORDER BY timestamp):
| Window Function | What it computes for each row |
|---|---|
ROW_NUMBER() OVER (PARTITION BY equipment ORDER BY start) | The 1-based chronological incident sequence number for that equipment. |
LAG(last_seen, 1) OVER (PARTITION BY equipment ORDER BY start) | The end time of the previous outage for this equipment (to compute days since last repair). |
COUNT(*) OVER (PARTITION BY station ORDER BY start ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) | The cumulative count of prior outages at this station, excluding the current event. |
Predict: why is using LEAD(start, 1) OVER (PARTITION BY equipment ORDER BY start) fatal if used as a feature in a production model?
- LEAD looks into future rows: at prediction time today, future outages have not happened yet (data leakage)
- LEAD is not supported in standard SQL
- LEAD always returns NULL
LEAD fetches values from subsequent, chronologically future rows. Using future event dates to predict current repair difficulty is blatant future data leakage: the feature will appear wildly predictive during training, but will be completely unavailable in production.Window functions calculate historical trends and sequence counts per entity without collapsing individual training rows.
5. As-of temporal joins: the golden rule of ML data
The single most destructive error in machine learning feature pipelines is calculating global aggregates over the entire dataset and joining them back onto historical rows:
-- LEAKAGE TRAP: Global aggregate computed across past AND future!
SELECT o.*, s.total_2026_outages
FROM outages o
JOIN (
SELECT station, COUNT(*) AS total_2026_outages
FROM outages
GROUP BY station
) s ON o.station = s.station;
In the query above, an outage in September is given the station's total outage count through December. The model learns that high outage counts correlate with late-year behavior, memorizes the future, and fails completely when deployed. The fix is an as-of join: features for an event at timestamp \(t\) must only count events that occurred strictly before \(t\):
Why as-of joins and point-in-time correctness are the golden rule of feature engineering
- The causality constraint. Physical reality flows forward in time. A model deployed on a live server at 2:00 PM today only has access to database records stamped \(\le \text{2:00 PM}\).
- Silent leakage kills models in production. When future rows leak into features, training loss drops effortlessly and validation accuracy looks suspiciously high. But in production, the future features are absent or unpopulated, causing catastrophic prediction drift.
- Window boundaries. Using
ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDINGguarantees that the current row's outcome is not included in its own historical feature aggregate.
Where it breaks: null joins, accidental cartesian explosions, and silent future leakage
- Cartesian product explosions (m × n). If you join two tables on a non-unique column without adequate deduplication, one outage matching five station records duplicates the outage five times. Always check row counts:
SELECT COUNT(*)before and after joining. - Time zone mismatches. Joining a UTC log table to an Eastern Time metadata table shifts timestamps by 4 to 5 hours. Late-night outages leak into the following day's predictions. Always standardize to UTC or consistent local timestamps.
- Silent NULL propagation. In SQL, any arithmetic with
NULLyieldsNULL(e.g.10 + NULL = NULL). UseCOALESCE(val, 0)when calculating sums or ratios so missing metadata doesn't turn entire feature rows into NaNs.
6. SQL next to pandas: the production division of labor
In modern ML platforms, SQL and pandas work as a tag team:
| Task | Where to do it | Why |
|---|---|---|
| Filter 100M rows to 50k relevant rows | SQL (Database) | Database indexes, columnar pruning, and cluster engines filter gigabytes in milliseconds without loading into RAM. |
| Enrich with relational metadata | SQL (Database) | Optimized hash joins and foreign key lookups on the storage server. |
| Point-in-time rolling aggregates | SQL (Window functions) | Declarative window execution inside the warehouse. |
| Nonlinear feature math & encodings | pandas / NumPy | Vectorized array operations, log transforms, one-hot encoding, and scikit-learn pipelines. |
| Model training & hyperparameter tuning | scikit-learn / PyTorch | CPU/GPU tensor execution. |
SQL handles heavy filtering, joining, and point-in-time windowing at the database layer; pandas and scikit-learn handle feature transforms and modeling.
All chapters: AI from scratch · Previous: pandas and scikit-learn · Next: Optimizers and schedules.
Last updated