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 ClauseWhat it doespandas Equivalent
SELECT col1, col2Picks which columns to keepdf[["col1", "col2"]]
WHERE conditionFilters rows matching criteriadf[df["kind"] == "EL"]
ORDER BY col DESCSorts rows by valuesdf.sort_values("col", ascending=False)
LIMIT nTakes the top n rowsdf.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?

Escalators are denoted by 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:

stationtotal_outages
Lexington Av/63 St24
42St/Port Authority-Bus Terminal18
61 St-Woodside15
Coney Island-Stillwell Av14
Grand Central-42 St12

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?

The database engine evaluates 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 TypeBehaviorRisk in Machine Learning
LEFT JOINKeeps all left rows; fills missing right columns with NULLRecommended: Preserves all training rows; missing metadata becomes imputable NaNs.
INNER JOINKeeps only rows present in both tablesDangerous: 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?

If 5% of stations in your outage log have a slight spelling difference (e.g. "61 St-Woodside" vs "Woodside"), an 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 FunctionWhat 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 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
  1. 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}\).
  2. 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.
  3. Window boundaries. Using ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING guarantees 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

6. SQL next to pandas: the production division of labor

In modern ML platforms, SQL and pandas work as a tag team:

TaskWhere to do itWhy
Filter 100M rows to 50k relevant rowsSQL (Database)Database indexes, columnar pruning, and cluster engines filter gigabytes in milliseconds without loading into RAM.
Enrich with relational metadataSQL (Database)Optimized hash joins and foreign key lookups on the storage server.
Point-in-time rolling aggregatesSQL (Window functions)Declarative window execution inside the warehouse.
Nonlinear feature math & encodingspandas / NumPyVectorized array operations, log transforms, one-hot encoding, and scikit-learn pipelines.
Model training & hyperparameter tuningscikit-learn / PyTorchCPU/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