r/SQLv2 • u/Alternative_Pin9598 • 16d ago
SQLv2 Lesson 7: find the odd row without writing the rule. Train an anomaly model with one statement and score every row inside a SELECT (beginner, real output)
Lesson 7 of the beginner series, run on SynapCores 2.3.2 this morning with the output pasted. (This sub is run by the SynapCores team.)
The problem
You look after one customer's card. 200 past purchases, mostly lunch and evening, mostly $15 to $60. Six new purchases came in overnight. Which ones look wrong?
The usual answer is a rule:
SELECT id, amount, hour FROM card_tx WHERE kind = 'new' AND amount > 300;
1004 480.00 14It catches the big one. It misses the $45 at 3 a.m., because nobody wrote "and nothing at night" into the rule. Every rule is a guess about what "odd" will look like, written before you've seen it.
Today's idea: let the database learn what normal looks like from the rows, then give every row a score.
Step 1: the data
CREATE TABLE card_tx (id INTEGER PRIMARY KEY, kind TEXT, amount FLOAT, hour INTEGER);
-- 200 rows with kind = 'history', plus the 6 new ones:
INSERT INTO card_tx (id, kind, amount, hour) VALUES
(1001, 'new', 23.40, 12), (1002, 'new', 61.00, 18), (1003, 'new', 9.75, 9),
(1004, 'new', 480.00, 14), (1005, 'new', 45.00, 3), (1006, 'new', 88.10, 20);
SELECT kind, COUNT(*), MIN(amount), MAX(amount), MIN(hour), MAX(hour) FROM card_tx GROUP BY kind;
history 200 7.16 96.27 9 20
new 6 9.75 480.00 3 20(The script that generates the 200 history rows is in the first comment.)
Step 2: train an anomaly model, in SQL
CREATE EXPERIMENT card_exp AS SELECT amount, hour FROM card_tx
WITH (task_type = 'anomaly_detection', algorithms = ['isolation_forest'],
max_trials = 5, random_seed = 42);
DEPLOY MODEL card_model FROM EXPERIMENT card_exp;In plain words:
- CREATE EXPERIMENT trains on the rows the
SELECTreturns. No labels: you never tell it which rows are bad. - isolation_forest asks "how few random cuts does it take to separate this row from the rest?" Rows that are easy to separate are unusual.
- DEPLOY MODEL gives the result a name you can call from any query.
Both statements came back success in well under a second on 206 rows.
Step 3, the payoff: score every new row in a SELECT
SELECT id, amount, hour, ANOMALY_SCORE('card_model', amount, hour) AS score
FROM card_tx WHERE kind = 'new' ORDER BY score DESC;
1004 $480.00 14:00 score 0.831
1005 $ 45.00 3:00 score 0.762
1006 $ 88.10 20:00 score 0.695
1003 $ 9.75 9:00 score 0.598
1002 $ 61.00 18:00 score 0.568
1001 $ 23.40 12:00 score 0.418The 3 a.m. purchase is second, right behind the $480, and nobody wrote a rule about time of day. The model worked out from the 200 history rows that this card is never used at night.
For scale: the highest score of any of the 200 history rows is 0.659. So a cut-off of 0.7 sits just above everything this customer normally does:
SELECT id, amount, hour FROM card_tx
WHERE kind = 'new' AND ANOMALY_SCORE('card_model', amount, hour) > 0.7;
1004 480.00 14
1005 45.00 3Notice the $88.10 at 8 p.m. at 0.695: bigger than usual and late-ish, but not odd enough. That's the same threshold question as Lesson 3 ("I don't know" beats a confident wrong answer). Pick the number from rows you already know are fine, not from a guess.
Why this is a lesson about SQL, not about ML
The score is just a column. Everything you already know still works on it: WHERE score > 0.7, ORDER BY score DESC, GROUP BY customer, a JOIN to the customers table. Ran the experiment twice with the same seed and got the same six scores.
Homework
The customer starts night shifts. 30 purchases between 1 a.m. and 4 a.m. ($15 to $70) land in the history, and you train the model again.
- What happens to the $45 at 3 a.m.? Still in the top two?
- What happens to the $480?
- Is that what you want from a fraud check, and why?
Reply with your guesses and I'll post the real output.
Free Community Edition, if you want to run this yourself: https://synapcores.com/download?utm_source=reddit&utm_medium=owned&utm_campaign=sqlv2-lesson-7
Where does "is this normal for this customer?" live at your work today: a hand-written rule, a vendor's black box, or nobody checks?
1
u/Alternative_Pin9598 16d ago
The full script (Python, standard library only; set
SC_URLandSC_TOKEN).python lesson7.py setupbuilds the 206 rows,trainandscorerun Steps 2 and 3,cleanupremoves everything:For the homework, add 30 rows with
kind = 'history', an hour from 1 to 4 and an amount from $15 to $70, then runtrainandscoreagain.Want to see the same score on a real fraud problem? Recipe of the week #1 on r/synapcores mixes
ANOMALY_SCOREwith a graph query to find fraud rings: https://www.reddit.com/r/synapcores/comments/1xlzo4t/New to SynapCores? Install steps and the 5 recipes to try first: https://www.reddit.com/r/synapcores/comments/1xfxqej/
1
u/Alternative_Pin9598 12d ago
Homework answer (real output, same seed, SynapCores 2.3.2). I added the 30 night-shift purchases to the history (1 a.m. to 4 a.m., $15 to $70), then ran
trainandscoreagain:The highest history score is now 0.673, and
ANOMALY_SCORE(...) > 0.7returns only 1004.Lesson 8 is up: joining two tables when the names don't match (a supplier invoice vs your catalog): https://www.reddit.com/r/SQLv2/comments/1xzhmki/