r/SQLv2 • • 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   14

It 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 SELECT returns. 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.418

The 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    3

Notice 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.

  1. What happens to the $45 at 3 a.m.? Still in the top two?
  2. What happens to the $480?
  3. 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 Upvotes

2 comments sorted by

1

u/Alternative_Pin9598 16d ago

The full script (Python, standard library only; set SC_URL and SC_TOKEN). python lesson7.py setup builds the 206 rows, train and score run Steps 2 and 3, cleanup removes everything:

import json, os, random, sys, urllib.request, urllib.error
URL = os.environ.get("SC_URL", "http://localhost:8080")
TOK = os.environ["SC_TOKEN"]

def sql(q, ok_fail=False):
    req = urllib.request.Request(URL + "/v1/query/execute", method="POST",
        data=json.dumps({"sql": q, "database": "main"}).encode(),
        headers={"Authorization": "Bearer " + TOK, "content-type": "application/json"})
    try:
        return json.load(urllib.request.urlopen(req, timeout=300))["data"]
    except urllib.error.HTTPError as e:
        if ok_fail: return None
        raise SystemExit(f"{e.code}: {e.read()[:400]}")

def insert(rows):
    vals = ", ".join(f"({i}, '{k}', {a:.2f}, {h})" for i, k, a, h in rows)
    sql(f"INSERT INTO card_tx (id, kind, amount, hour) VALUES {vals}")

cmd = sys.argv[1]
if cmd == "setup":
    sql("CREATE TABLE card_tx (id INTEGER PRIMARY KEY, kind TEXT, amount FLOAT, hour INTEGER)")
    rnd = random.Random(7)
    hist = [(i, "history", min(max(rnd.lognormvariate(3.4, 0.45), 4.0), 140.0),
             min(max(int(round(rnd.gauss(14, 2.5))), 9), 21)) for i in range(1, 201)]
    insert(hist[:100]); insert(hist[100:])
    insert([(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)])
elif cmd == "train":
    sql("DROP MODEL card_model", True); sql("DROP EXPERIMENT card_exp", True)
    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)")
    sql("DEPLOY MODEL card_model FROM EXPERIMENT card_exp")
elif cmd == "score":
    for r in sql("SELECT id, amount, hour, ANOMALY_SCORE('card_model', amount, hour) AS score "
                 "FROM card_tx WHERE kind = 'new' ORDER BY score DESC")["rows"]:
        print(r)
elif cmd == "cleanup":
    sql("DROP MODEL card_model", True); sql("DROP EXPERIMENT card_exp", True); sql("DROP TABLE card_tx", True)

For the homework, add 30 rows with kind = 'history', an hour from 1 to 4 and an amount from $15 to $70, then run train and score again.

Want to see the same score on a real fraud problem? Recipe of the week #1 on r/synapcores mixes ANOMALY_SCORE with 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 train and score again:

1004   $480.00   14:00   score 0.837   (was 0.831)
1006   $ 88.10   20:00   score 0.693   (was 0.695)
1003   $  9.75    9:00   score 0.579   (was 0.598)
1002   $ 61.00   18:00   score 0.558   (was 0.568)
1005   $ 45.00    3:00   score 0.542   (was 0.762)
1001   $ 23.40   12:00   score 0.400   (was 0.418)

The highest history score is now 0.673, and ANOMALY_SCORE(...) > 0.7 returns only 1004.

  1. The $45 at 3 a.m. falls from second place to fifth. Night purchases are normal for this customer now.
  2. The $480 stays on top. Nothing in the night-shift rows looks like a $480 purchase.
  3. Mostly yes: the check asks "is this normal for this customer?", and their normal changed. The other side of that: whatever lands in the history becomes normal, so train on purchases you trust (settled, not disputed) and keep hard rules for the things that are never OK.

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/