r/SQLv2 • • 6d ago

SQLv2 Lesson 8: JOIN two tables when the names don't match. "=" matches 0 of 8 invoice lines; a JOIN by meaning matches 7, skips the chair you don't sell, and finds $129 over list price (beginner, real output)

Lesson 8 of the beginner series, run on SynapCores 2.3.2 this morning with the output pasted. (This sub is run by the SynapCores team.)

Lesson 7 homework, answered: after 30 night-shift purchases, the $45 at 3 a.m. drops from 0.762 to 0.542 and the $480 stays on top at 0.837 (full output under Lesson 7).

The problem

A new supplier's invoice has 8 lines, written their way. Your catalog has your names and your list prices. Which of your products is each line, and did they charge list price?

Step 1: two tables

CREATE TABLE catalog (id INTEGER PRIMARY KEY, name TEXT,
  list_price FLOAT, vec VECTOR(384));
CREATE TABLE invoice_lines (line INTEGER PRIMARY KEY, item TEXT,
  qty INTEGER, unit_price FLOAT, vec VECTOR(384));

8 products go in catalog ("USB-C laptop charger, 65 W" at 39.00, ...), the supplier's 8 lines in invoice_lines ("Type-C power adapter 65W for notebooks", 10 at 41.50, ...). All 16 INSERTs are in the first comment.

The usual JOIN:

SELECT COUNT(*) FROM invoice_lines i JOIN catalog c ON LOWER(i.item) = LOWER(c.name);

0

Not one. Same products, different words.

Step 2: a meaning vector for every row (Lesson 1)

UPDATE catalog SET vec = EMBED(name);
UPDATE invoice_lines SET vec = EMBED(item);

Step 3: JOIN by meaning

Every line against every product (CROSS JOIN), keep the best one per line (ROW_NUMBER, as in Lesson 3):

WITH best AS (
  SELECT i.line, c.id, COSINE_SIMILARITY(i.vec, c.vec) AS sim,
    ROW_NUMBER() OVER (PARTITION BY i.line
      ORDER BY COSINE_SIMILARITY(i.vec, c.vec) DESC) AS rn
  FROM invoice_lines i CROSS JOIN catalog c)
SELECT i.line, i.item, ROUND(b.sim, 2) AS sim,
  CASE WHEN b.sim >= 0.43 THEN c.name ELSE 'NO MATCH: ask purchasing' END AS matched
FROM best b JOIN invoice_lines i ON i.line = b.line JOIN catalog c ON c.id = b.id
WHERE b.rn = 1 ORDER BY i.line;

1  Type-C power adapter 65W for notebooks  0.72  USB-C laptop charger, 65 W
2  Cordless optical mouse, blk  0.49  Wireless mouse, black
3  2m high speed HDMI lead  0.64  HDMI cable, 2 m
4  UHD 27in display  0.60  27-inch 4K monitor
5  Keyboard w/ mechanical switches, ANSI  0.63  Mechanical keyboard, US layout
6  Ergonomic mesh office chair  0.37  NO MATCH: ask purchasing
7  ANC headphones with boom mic  0.50  Noise-cancelling headset with microphone
8  Dock, USB-C, 2x HDMI out  0.70  USB-C docking station, dual display

Seven right matches, including "UHD 27in display" to "27-inch 4K monitor", which share no word at all.

Where does 0.43 come from?

You don't sell office chairs, but CROSS JOIN still finds the chair a "best" product: the laptop stand, at 0.37. The seven real matches score 0.49 to 0.72, and 0.43 sits in the middle of that gap (Lesson 3: pick the number from rows you can check). Without it, two office chairs get booked as laptop stands.

Step 4, the payoff: plain SQL again

Every line now has a product id. Which lines are above list price?

WITH best AS (... same as Step 3 ...)
SELECT i.item, c.name, i.qty, i.unit_price, c.list_price,
  (i.unit_price - c.list_price) * i.qty AS over_list
FROM best b JOIN invoice_lines i ON i.line = b.line JOIN catalog c ON c.id = b.id
WHERE b.rn = 1 AND b.sim >= 0.43 AND i.unit_price > c.list_price
ORDER BY over_list DESC;

UHD 27in display  4 x 315.00  list 289.00  over 104.00
Type-C power adapter 65W for notebooks  10 x 41.50  list 39.00  over 25.00

$129 over list on two lines, through a JOIN that = couldn't make. The meaning part is one condition; everything after it (prices, SUM, GROUP BY supplier) is SQL you already know. Ran it twice from scratch: same scores, same matches.

Homework

Next week the supplier adds 'Wireless mouse, white', 10 at 19.00. You only stock the black one.

  1. Which product does the JOIN pick, and is the score above 0.43?
  2. Is it higher or lower than the real mouse match on line 2 (0.49)?
  3. What would you add to the query so this line goes to a human?

Reply with your guesses and I'll post the real output.

Free Community Edition: https://synapcores.com/download?utm_source=reddit&utm_medium=owned&utm_campaign=sqlv2-lesson-8

Where do you match names that don't line up today: a VLOOKUP, a mapping table someone keeps by hand, or fuzzy string matching?

1 Upvotes

2 comments sorted by

1

u/Alternative_Pin9598 6d ago

The full script (Python, standard library only; set SC_URL and SC_TOKEN). python lesson8.py setup creates both tables, inserts the 16 rows and adds the vectors; match and prices run Steps 3 and 4; cleanup drops everything:

import json, os, 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]}")

CATALOG = [(101, "USB-C laptop charger, 65 W", 39.00), (102, "Wireless mouse, black", 19.00),
           (103, "HDMI cable, 2 m", 9.00), (104, "27-inch 4K monitor", 289.00),
           (105, "Mechanical keyboard, US layout", 79.00), (106, "USB-C docking station, dual display", 129.00),
           (107, "Noise-cancelling headset with microphone", 99.00), (108, "Aluminium laptop stand", 35.00)]
INVOICE = [(1, "Type-C power adapter 65W for notebooks", 10, 41.50), (2, "Cordless optical mouse, blk", 20, 19.00),
           (3, "2m high speed HDMI lead", 50, 9.00), (4, "UHD 27in display", 4, 315.00),
           (5, "Keyboard w/ mechanical switches, ANSI", 6, 79.00), (6, "Ergonomic mesh office chair", 2, 240.00),
           (7, "ANC headphones with boom mic", 8, 99.00), (8, "Dock, USB-C, 2x HDMI out", 5, 129.00)]

BEST = """WITH best AS (
  SELECT i.line, c.id, COSINE_SIMILARITY(i.vec, c.vec) AS sim,
    ROW_NUMBER() OVER (PARTITION BY i.line ORDER BY COSINE_SIMILARITY(i.vec, c.vec) DESC) AS rn
  FROM invoice_lines i CROSS JOIN catalog c)
"""
MATCH = BEST + """SELECT i.line, i.item, ROUND(b.sim, 2) AS sim,
  CASE WHEN b.sim >= 0.43 THEN c.name ELSE 'NO MATCH: ask purchasing' END AS matched
FROM best b JOIN invoice_lines i ON i.line = b.line JOIN catalog c ON c.id = b.id
WHERE b.rn = 1 ORDER BY i.line"""
PRICES = BEST + """SELECT i.item, c.name, i.qty, i.unit_price, c.list_price,
  (i.unit_price - c.list_price) * i.qty AS over_list
FROM best b JOIN invoice_lines i ON i.line = b.line JOIN catalog c ON c.id = b.id
WHERE b.rn = 1 AND b.sim >= 0.43 AND i.unit_price > c.list_price
ORDER BY over_list DESC"""

cmd = sys.argv[1]
if cmd == "setup":
    sql("CREATE TABLE catalog (id INTEGER PRIMARY KEY, name TEXT, list_price FLOAT, vec VECTOR(384))")
    sql("CREATE TABLE invoice_lines (line INTEGER PRIMARY KEY, item TEXT, qty INTEGER, unit_price FLOAT, vec VECTOR(384))")
    sql("INSERT INTO catalog (id, name, list_price) VALUES " +
        ", ".join(f"({i}, '{n}', {p:.2f})" for i, n, p in CATALOG))
    sql("INSERT INTO invoice_lines (line, item, qty, unit_price) VALUES " +
        ", ".join(f"({l}, '{t}', {q}, {p:.2f})" for l, t, q, p in INVOICE))
    print("exact-name JOIN matches:", sql("SELECT COUNT(*) FROM invoice_lines i JOIN catalog c "
                                          "ON LOWER(i.item) = LOWER(c.name)")["rows"][0][0])
    sql("UPDATE catalog SET vec = EMBED(name)")
    sql("UPDATE invoice_lines SET vec = EMBED(item)")
elif cmd == "match":
    for r in sql(MATCH)["rows"]: print(r)
elif cmd == "prices":
    rows = sql(PRICES)["rows"]
    for r in rows: print(r)
    print("total over list:", sum(r[5] for r in rows))
elif cmd == "cleanup":
    sql("DROP TABLE invoice_lines", True); sql("DROP TABLE catalog", True)

For the homework, add the line and its vector, then run match again:

INSERT INTO invoice_lines (line, item, qty, unit_price) VALUES (9, 'Wireless mouse, white', 10, 19.00);
UPDATE invoice_lines SET vec = EMBED(item) WHERE line = 9;

When some supplier lines do carry your SKU, let the exact code win and use meaning for the rest. Ask the maintainers #3 on r/synapcores does both in one SELECT: https://www.reddit.com/r/synapcores/comments/1xva6ko/

New to SynapCores? Install steps and the 5 recipes to try first: https://www.reddit.com/r/synapcores/comments/1xfxqej/

1

u/Alternative_Pin9598 3d ago

Homework answer (real output, SynapCores 2.5.1). I added (9, 'Wireless mouse, white', 10, 19.00), ran UPDATE invoice_lines SET vec = EMBED(item) WHERE line = 9, then match again. Lines 1 to 8 didn't change; the new one:

9  Wireless mouse, white  0.85  Wireless mouse, black
  1. The black mouse, at 0.85 (0.846 unrounded), well above 0.43.
  2. Higher. Not just higher than line 2 (0.49): it's the highest score on the whole invoice. Its runner-up is the charger at 0.25, so it isn't even a close call.
  3. Not a higher threshold: one high enough to stop it (above 0.85) drops all 7 real matches too. Similarity measures "same kind of thing", and a white mouse is the same kind of thing as a black one. What you add is a second question, "do these two descriptions contradict each other?": NLI_CLASSIFY('nli-default', 'Wireless mouse, black', 'Wireless mouse, white') scores contradiction 0.998, and the real mouse line ('Cordless optical mouse, blk') 0.018.

Lesson 9 puts that check into the JOIN, with three more look-alikes (a 5 m cable, a 100 W charger, a UK-layout keyboard): https://www.reddit.com/r/SQLv2/comments/1y1zklg/