PURE SQL MACHINE LEARNING · NO PYTHON

A query can be more than data retrieval. It can be the model.

Machine learning begins with representation, distance, probability, optimization and aggregation. SQL already has those building blocks. This lab opens the black box by rebuilding six model families from relational operations.

01 · REPRESENTCASE · one-hot · scale
02 · COMPAREdistance · likelihood
03 · LEARNaggregate · iterate
04 · DECIDErank · vote · threshold

SIX LIVE FAMILIES

Different algorithms, the same relational vocabulary.

Press Run SQL to execute each complete model pipeline on the server. Results and the exact SQL are returned; source rows stay inside the engine.

k-Nearest Neighbors

DISTANCE · TOP-K · VOTE

Encode rows, compute Euclidean distance, rank five neighbors and vote with GROUP BY.

10,000-row bounded runtime
EXECUTED SQL
Select Run pure SQL.

Naive Bayes

PRIOR · LIKELIHOOD · LOG SCORE

Estimate priors and likelihoods with aggregates, apply Laplace smoothing and sum log probabilities.

10,000-row bounded runtime
EXECUTED SQL
Select Run pure SQL.

Linear Regression

COVARIANCE · SLOPE · INTERCEPT

Fit slope, intercept and R² from SQL aggregate statistics and predict in the same statement.

10,000-row bounded runtime
EXECUTED SQL
Select Run pure SQL.

k-means

ASSIGN · CENTROID · REPEAT

Use joins for point-centroid distance, a window rank for assignment and GROUP BY for new centroids.

10,000-row bounded runtime
EXECUTED SQL
Select Run pure SQL.

Association Rules

SUPPORT · CONFIDENCE · LIFT

Self-join items within baskets and derive support, confidence and lift from grouped counts.

10,000-row bounded runtime
EXECUTED SQL
Select Run pure SQL.

Statistical Anomaly

MEAN · STANDARD DEVIATION · Z-SCORE

Learn mean and standard deviation, score every observation and rank unusual rows.

10,000-row bounded runtime
EXECUTED SQL
Select Run pure SQL.

EMBEDDED EXCEL WORKSHEET

The original worksheet, translated into a web-readable model.

The 2022 workbook teaches the same dataset through probability and distance. Tabs below preserve that learning order; download the Excel file to inspect and modify the formulas.

Play Golf · 14 training examples

No.OutlookTemperatureHumidityWindyPlay
1sunnyhothighfalseno
2sunnyhothightrueno
3overcasthothighfalseyes
4rainymildhighfalseyes
5rainycoolnormalfalseyes
6rainycoolnormaltrueno
7overcastcoolnormaltrueyes
8sunnymildhighfalseno
9sunnymildnormalfalseyes
10rainymildnormalfalseyes
11sunnymildnormaltrueyes
12overcastmildhightrueyes
13overcasthotnormalfalseyes
14rainymildhightrueno

Naive Bayes · rainy, cool, high, true

ClassPriorP(rainy|class)P(cool|class)P(high|class)P(windy=true|class)Original product
yes9/143/92/93/93/90.00823
no5/142/51/54/53/50.03840
Workbook view

Visible multiplication makes conditional evidence easy to follow.

Web SQL upgrade

Adds class prior, Laplace smoothing and log scores so unseen values and underflow are handled explicitly.

kNN · sunny, 0.82, 0.83, not windy · k=5

NeighborDistanceClass
10.0361no
80.1562no
90.1838yes
21.0026no
111.0108yes

Vote: no = 3, yes = 2 → prediction = no

HOW SQL BECOMES ML

The model is stored logic, learned state—or both.

Pure SQL does not mean every algorithm is equally elegant or scalable. It means the complete transformation from training rows to decision is expressed and executed inside the data engine.

TABLEtraining rows
CTE / VIEWfeature contract
AGGREGATElearned statistics
WINDOW / JOINcompare and rank
RELATIONprediction + evidence

Where pure SQL is strong—and where honesty matters

  • Excellent for transparent baselines, small-to-medium tabular problems, governed data and teaching algorithm mechanics.
  • kNN is expensive at scoring time: a naive query compares each query row with every training row.
  • Iterative methods need bounded recursion, procedures or explicitly unrolled steps; convergence must be measured.
  • Deep neural networks, GPU training and complex automatic differentiation are not sensible targets for hand-written SQL.

RELATED LESSONS

Use pure SQL to understand; use platforms to operate.

Continue to Declarative ML for the wider ecosystem, MADlib for mature in-database algorithms, and DuckDB × ClickHouse for execution-boundary comparison.

NEXT PURE SQL LAB

Turn relationships into ranked recommendations.

Continue with seven SQL-only recommender methods: popularity, graph co-occurrence, collaborative filtering, content, time decay and hybrid ranking.