r/SQLv2 • • Oct 02 '25

πŸ› οΈ Welcome to r/SQLv2 – Community Guide

1 Upvotes

SQLv2 is the open standard that extends SQL with AI, vector search, and inference inside the database engine. This community is here to share knowledge, recipes, and discussions around building AI-native applications with SQLv2.

πŸ”‘ What You’ll Find Here

  • Recipes & Examples – step-by-step queries (sentiment analysis, embeddings, anomaly detection, recommendations).
  • Discussions – share challenges, ask questions, or suggest improvements to the SQLv2 spec.
  • Benchmarks – performance results, cost comparisons, latency tests.
  • Updates – announcements on spec updates, tooling, and SynapCores beta.
  • Contributions – community-created queries, tutorials, or integrations.

πŸ“Œ Posting Guidelines

  1. Stay on topic – posts should relate to SQLv2, AI in databases, ML+SQL workflows, or vector search.
  2. No spam or ads – vendor pitches will be removed.
  3. Use clear titles – e.g., β€œRecipe: Fraud detection with SQLv2” or β€œDiscussion: Should inference be part of SELECT?”
  4. Credit sources – if you share a benchmark, include dataset + environment details.
  5. Respectful discussion – disagreements are welcome, personal attacks are not.

πŸš€ How to Contribute

  • Try out a recipe at synapcores.com/sqlv2 and post your results.
  • Start a discussion thread about a pain point SQLv2 might solve.
  • Share real-world use cases where SQLv2 reduces ETL, cost, or latency.
  • Suggest new operators or functions you’d like to see in the spec.

πŸ“… Posting Cadence

  • Weekly recipes from moderators.
  • Bi-weekly discussions for open Q&A.
  • Monthly community spotlight featuring member-contributed queries.

🎯 Our Goal

Make SQLv2 the standard way to unify SQL + AI in one language, supported by an active community of engineers, researchers, and builders.


r/SQLv2 • • 3d ago

SQLv2 Lesson 9: similar isn't the same item. A white mouse scores 0.85 against your black one, the real mouse line only 0.49. One contradiction check in the JOIN catches it and 3 more look-alikes (beginner, real output)

1 Upvotes

Lesson 9 of the beginner series, run on SynapCores 2.5.1 this morning. (This sub is run by the SynapCores team.)

Lesson 8 homework, answered: 'Wireless mouse, white' matches 'Wireless mouse, black' at 0.85, higher than all 7 real matches on that invoice (the real mouse line: 0.49). Full output under Lesson 8.

Similarity asks: same kind of thing? A white and a black mouse are. To book stock or check prices, you need: same item?

Step 1: next week's invoice

Lesson 8's tables plus 5 new supplier lines (lines 9 to 13; INSERTs in the first comment). You stock the black mouse, 2 m cable, 65 W charger, US-layout keyboard and aluminium stand.

Lesson 8's JOIN matches all five, at 0.85 to 0.94. Four are wrong, and no threshold can split them off: real matches sit both below (0.49 to 0.72) and above (the stand, 0.94).

Step 2: a different question

NLI (natural language inference) is a small model in the engine that scores whether one text contradicts another:

SELECT ROUND(JSON_EXTRACT(NLI_CLASSIFY('nli-default',
  'Wireless mouse, black', 'Wireless mouse, white'), '$.scores.contradiction'), 3);

0.998

The real mouse line, 'Cordless optical mouse, blk': 0.018.

Step 3: both checks in one query

WITH best AS (... same as Lesson 8 ...),
checked AS (
  SELECT i.line, b.id, i.item, c.name, b.sim,
    JSON_EXTRACT(NLI_CLASSIFY('nli-default', c.name, i.item), '$.scores.contradiction') AS c1,
    JSON_EXTRACT(NLI_CLASSIFY('nli-default', i.item, c.name), '$.scores.contradiction') AS c2
  FROM best b JOIN invoice_lines i ON i.line = b.line JOIN catalog c ON c.id = b.id
  WHERE b.rn = 1)
SELECT line, item, ROUND(sim, 2) AS sim, ROUND(c1, 2) AS c1, ROUND(c2, 2) AS c2,
  CASE WHEN sim < 0.43 THEN 'NO MATCH: ask purchasing'
       WHEN c1 > 0.5 AND c2 > 0.5 THEN 'DIFFERENT ITEM: ask purchasing'
       ELSE name END AS matched
FROM checked ORDER BY line;

1  Type-C power adapter 65W for notebooks  0.72 0.00 0.05  USB-C laptop charger, 65 W
2  Cordless optical mouse, blk  0.49 0.02 0.00  Wireless mouse, black
3  2m high speed HDMI lead  0.64 0.00 0.01  HDMI cable, 2 m
4  UHD 27in display  0.60 0.00 0.00  27-inch 4K monitor
5  Keyboard w/ mechanical switches, ANSI  0.63 0.01 0.99  Mechanical keyboard, US layout
6  Ergonomic mesh office chair  0.37 1.00 1.00  NO MATCH: ask purchasing
7  ANC headphones with boom mic  0.50 0.61 0.03  Noise-cancelling headset with microphone
8  Dock, USB-C, 2x HDMI out  0.70 0.00 0.00  USB-C docking station, dual display
9  Wireless mouse, white  0.85 1.00 1.00  DIFFERENT ITEM: ask purchasing
10  HDMI cable, 5 m  0.92 1.00 1.00  DIFFERENT ITEM: ask purchasing
11  USB-C laptop charger, 100 W  0.90 1.00 1.00  DIFFERENT ITEM: ask purchasing
12  Mechanical keyboard, UK layout  0.85 1.00 1.00  DIFFERENT ITEM: ask purchasing
13  Laptop stand, aluminum  0.94 0.00 0.00  Aluminium laptop stand

Why both ways? NLI takes the first text as given and checks the second against it, so a pair can clash one way only (lines 5 and 7). Each wrong item clashes both ways (9 to 12). Requiring both keeps all 8 real matches.

Step 4, the payoff: Lesson 8's price check

On the new invoice: $429 over list.

USB-C laptop charger, 100 W  10 x 59.00 vs 39.00  +200.00
UHD 27in display  4 x 315.00 vs 289.00  +104.00
HDMI cable, 5 m  20 x 14.00 vs 9.00  +100.00
Type-C power adapter 65W for notebooks  10 x 41.50 vs 39.00  +25.00

$300 of that is the 100 W charger and the 5 m cable, priced as your 65 W charger and 2 m cable. Run it on checked k with AND NOT (k.c1 > 0.5 AND k.c2 > 0.5) and it's Lesson 8's $129 again. The white mouse and UK keyboard are at list price, so only Step 3 stops them being booked as the black mouse and US keyboard.

Homework

The supplier sends 'Wireless mouse', no colour, 10 at 19.00.

  1. Which product does the JOIN pick, and at what similarity?
  2. Does the contradiction check flag it?
  3. Should it? What would you do with a line that leaves a detail out?

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-9

What's the worst look-alike that got past your matching: wrong size, colour, wattage?


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)

1 Upvotes

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?


r/SQLv2 • • 10d 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)

1 Upvotes

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?


r/SQLv2 • • 11d ago

SQLv2 bonus lesson (2.5.0 is out): let a decision model label each ticket, store the labels as columns, then find the angry customers with plain GROUP BY / ORDER BY (beginner, real output)

1 Upvotes

Bonus lesson, because SynapCores 2.5.0 came out this week and it adds a fourth kind of AI answer to the engine. (This sub is run by the SynapCores team.)

The four kinds of answer, one engine

So far in this course you've used three:

  • ML: train a model on your rows and predict a number or a class (AutoML in SQL).
  • NLI: check whether a statement is backed by your own data.
  • LLM: write text, answer with citations, run an agent.

2.5.0 adds the fourth: decisions. Ask a question with fixed options and get back the option plus a probability for each one. No paragraph to parse. It runs on d1, a small decision model, through one endpoint: POST /v1/systemone.

Today's idea is simple and very SQL: let the model label each row, store the labels as normal columns, then answer business questions with the SQL you already know.

Step 1: one-time model download (~2.7 GiB)

synapcores --config gateway.toml pull d1:latest

Step 2: a table for the labels

CREATE TABLE ticket_triage (
  id INTEGER PRIMARY KEY,
  ticket TEXT,
  team TEXT,
  team_conf FLOAT,
  angry FLOAT
);

Step 3: ask two questions per ticket

The request body for one ticket:

{"model": "d1:latest",
 "state": "Your update deleted all my saved carts. Third time this month. I am done with this app.",
 "questions": {
   "route": {"type": "choice", "instructions": "Which team should handle this?",
             "criteria": {"billing": "payments/refunds/invoices", "shipping": "delivery", "technical": "bugs"}},
   "angry": {"type": "noul", "instructions": "Is the customer angry?"}}}

choice picks one option and gives a probability for every option. noul is a yes/no question and returns the probability of "yes". We ran six tickets and inserted each answer as a row:

id  team       conf  angry  ticket
1   billing    0.94  0.78   "charged my card twice ... TODAY or I dispute"
2   shipping   0.96  0.01   "could I change the delivery address on order 4471?"
3   technical  0.97  0.19   "app logs me out on the settings page. Annoying"
4   shipping   0.92  0.98   "tracking says 'label created' for 9 days"
5   billing    0.99  0.02   "invoice with our VAT number, please"
6   technical  0.87  0.91   "your update deleted my saved carts. Third time"

Step 4: now it's just SQL

Tickets and angry tickets per team:

SELECT team, COUNT(*) AS tickets,
       SUM(CASE WHEN angry > 0.5 THEN 1 ELSE 0 END) AS angry_tickets
FROM ticket_triage
GROUP BY team
ORDER BY team;

team       tickets  angry_tickets
billing    2        1
shipping   2        1
technical  2        1

Who should a senior agent call first?

SELECT id, team, ROUND(angry, 2) AS angry
FROM ticket_triage
WHERE angry > 0.5
ORDER BY angry DESC;

id  team       angry
4   shipping   0.98
6   technical  0.91
1   billing    0.78

Notice tickets 2 and 4: both go to shipping, but one is a polite question (0.01) and one is furious (0.98). A keyword rule on "shipping" can't tell them apart; a stored angry column can, and then WHERE and ORDER BY do the rest.

Why store the probability, not just yes/no? Because you can change the threshold later in SQL (angry > 0.8 for a stricter queue) without asking the model again.

Homework: add a third question, "refund": {"type": "noul", "instructions": "Is the customer asking for money back?"}, store it as a refund FLOAT column, and write a query for "angry AND wants a refund".

Learn which of the four answer types fits which problem: https://synapcores.com/learn/llm-vs-nli-vs-vectors/llm-vs-nli-vs-ml-vs-decision-model?utm_source=reddit&utm_medium=owned&utm_campaign=sqlv2-07

Practice the SQL part in your browser, no install: https://synapcores.com/playground?utm_source=reddit&utm_medium=owned&utm_campaign=sqlv2-07

What would you label first with a decision column: support tickets, reviews, or alerts?


r/SQLv2 • • 13d ago

SQLv2 Lesson 6: your first learning goal. The database tries two sources, checks each answer with SQL, keeps score, and switches when the policy changes (beginner)

1 Upvotes

Lesson 6 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

Your support bot answers "how long do refunds take?" from the FAQ or the policy page. Only one is approved by legal at a time, and which one changes. Hard-code "use the policy page" and the bot breaks the day legal rewrites the FAQ instead.

What you want: try a source, check the answer against the database, keep score, prefer whatever has been passing. That's a learning goal.

Step 1: the data

CREATE TABLE refund_answers (source TEXT PRIMARY KEY, approved INTEGER, answer TEXT);
INSERT INTO refund_answers (source, approved, answer) VALUES
  ('faq', 0, 'Refunds take 5 business days.'),
  ('policy_page', 1, 'Refunds reach your card within 10 business days after we receive the item.');

Step 2: the goal

A goal = what you want done + ways to try it + a success check, sent as JSON to POST /v1/agents/goals. The important parts:

"task_type": "refund-question",  "learn": true,  "explore": 0.1,
"guardrails": {"allowed_actions": ["sql"]},
"steps": [{
  "action":       SELECT approved, answer FROM refund_answers WHERE source = 'faq'
  "alternatives": SELECT approved, answer FROM refund_answers WHERE source = 'policy_page'
  "acceptance":   {"kind": "json_equals", "pointer": "/rows/0/0", "expected": 1}
}]

In plain words:

  • Two strategies: FAQ first, policy page second.
  • Success check: first column of the first row must be 1 (approved). The database decides, not a model.
  • learn = true: keep a score per strategy for this task_type. Off unless you ask.
  • explore = 0.1: now and then try the other one anyway, so a change gets noticed.
  • guardrails: SQL only.

(Full goal JSON and the 20-line runner are in the first comment.)

Step 3: six customers ask the question

question 1: done   tried: faq -> policy_page
question 2: done   tried: policy_page
question 3: done   tried: policy_page
question 4: done   tried: policy_page
question 5: done   tried: policy_page
question 6: done   tried: policy_page

Question 1 tried the FAQ, failed the check (not approved), and fell back. From question 2 on, it goes straight to the policy page.

Step 4: look at what it learned (plain SQL)

SHOW AGENT POLICY;

Output for this task type (trimmed):

{"action": "sql:faq",         "count": 1, "reward_sum": -1.0, "mean": -1.0}
{"action": "sql:policy_page", "count": 6, "reward_sum":  6.0, "mean":  1.0}

Each try scores +1 (passed) or -1 (failed). A tally sheet you can query, not a trained model.

Step 5: legal changes the policy

UPDATE refund_answers SET approved = 0 WHERE source = 'policy_page';
UPDATE refund_answers SET approved = 1,
  answer = 'Refunds reach your card within 7 business days after we receive the item (new policy).'
WHERE source = 'faq';

Eight more customers ask:

question 7:  done   tried: policy_page -> faq
question 8:  done   tried: policy_page -> faq
question 9:  done   tried: policy_page -> faq
question 10: done   tried: faq
question 11: done   tried: faq
...
question 14: done   tried: faq

{"action": "sql:faq",         "count": 9, "reward_sum": 7.0, "mean": 0.78}
{"action": "sql:policy_page", "count": 9, "reward_sum": 3.0, "mean": 0.33}

Three fallbacks, then the score flips and the bot prefers the FAQ, with no code change. Every customer still got the approved answer, because the check ran on every try. And "success" is a check on your own data, so it means what you say it means.

Homework

Legal un-approves both sources (UPDATE refund_answers SET approved = 0;). Question 15 comes in.

  1. Does the bot answer? With what?
  2. What happens to the two scores?
  3. Is that the behaviour you want from a support bot, 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-6

Where does "which source is the approved one right now" live at your work: a flag in a table, a doc owner, or tribal knowledge?


r/SQLv2 • • 17d ago

SQLv2 Lesson 5: "who can help me, and who introduces us?" Graph hops + meaning search in one database (beginner)

1 Upvotes

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

The problem

Ana is a frontend dev. Her Kafka consumers keep falling behind and she needs help. Lessons 1-3 taught search by meaning, so let's find the right person:

CREATE TABLE people (name TEXT PRIMARY KEY, about TEXT, embedding VECTOR(384));
INSERT INTO people (name, about) VALUES
  ('Ana', 'Frontend developer. React, CSS, accessibility.'),
  ('Ben', 'Backend developer. Postgres tuning and slow query plans.'),
  ('Chloe', 'SRE. Keeps our Kafka clusters up and runs the on-call rota.'),
  ('Dev', 'Kafka contributor. Consumer lag, partitions and rebalancing.'),
  ('Eli', 'Designer. Figma and the design system.'),
  ('Fay', 'Product manager for onboarding.'),
  ('Gus', 'Platform engineer. Message queues, RabbitMQ, event streaming.'),
  ('Hana', 'Accountant. Payroll and expenses.');
UPDATE people SET embedding = EMBED(about);

SELECT name, ROUND(COSINE_SIMILARITY(embedding,
  EMBED('my Kafka consumers keep falling behind')), 2) AS score
FROM people WHERE name <> 'Ana' ORDER BY score DESC LIMIT 4;

Output:

name | score
Dev | 0.72
Chloe | 0.42
Gus | 0.20
Ben | 0.14

Dev is the best match on paper, but nobody Ana knows has ever met Dev. The real question is "who knows Kafka that I can actually reach", and the second half is a graph question: who is connected to whom.

Step 1: the "who knows whom" graph (same database)

SynapCores also speaks Cypher, the graph query language (nodes in round brackets, relationships in square brackets):

MERGE (ana:Person {name: "Ana"}) MERGE (ben:Person {name: "Ben"})
MERGE (ana)-[:KNOWS]->(ben);
-- 8 people, 6 links: Ana-Ben, Ana-Eli, Ben-Chloe, Eli-Fay, Fay-Gus, Dev-Hana
-- (full block in the first comment)

Same Query Editor, same endpoint as your SQL.

Step 2: everyone Ana can reach in 1 to 3 hops

MATCH p = (me:Person {name: 'Ana'})-[:KNOWS*1..3]-(x:Person)
WHERE x.name <> 'Ana'
RETURN x.name AS name, length(p) AS hops, [n IN nodes(p) | n.name] AS via
ORDER BY hops;

Output:

name | hops | via
Ben | 1 | Ana > Ben
Eli | 1 | Ana > Eli
Chloe | 2 | Ana > Ben > Chloe
Fay | 2 | Ana > Eli > Fay
Gus | 3 | Ana > Eli > Fay > Gus

[:KNOWS*1..3] means "follow KNOWS links one to three times". With no arrow on either end, the direction doesn't matter. Dev isn't in the list: no path from Ana reaches him.

Step 3: put both answers in one SQL query

Save the reachable people as a normal table, then one query asks both questions:

-- ana_reach(name, hops, via): the 5 rows above (INSERT in the first comment)

SELECT p.name, ROUND(COSINE_SIMILARITY(p.embedding, EMBED('my Kafka consumers keep falling behind')), 2) AS score, r.hops, r.via
FROM people p JOIN ana_reach r ON r.name = p.name
WHERE COSINE_SIMILARITY(p.embedding, EMBED('my Kafka consumers keep falling behind')) > 0.3
ORDER BY score DESC;

Output:

name | score | hops | via
Chloe | 0.42 | 2 | Ana > Ben > Chloe

One row, and it's actionable: ask Ben to introduce you to Chloe. The > 0.3 threshold (Lesson 3) keeps Gus (0.20) out, so the answer isn't padded with "kind of related" people.

What you just learned

  • Meaning search answers "who is about this?"
  • A graph answers "who is connected to whom, and through whom?"
  • [:KNOWS*1..3] walks 1 to 3 hops; nodes(p) gives you the introduction chain.
  • Both live in one engine, so the final answer is a plain SQL JOIN. No second database to sync.

Homework

Ben leaves the company tomorrow, so his KNOWS links go away:

MATCH (b:Person {name: 'Ben'})-[k:KNOWS]-() DELETE k;
  1. Who can Ana still reach in 1 to 3 hops?
  2. Refresh ana_reach and rerun Step 3. What comes back?
  3. Is that a bug or the right answer? (Hint: Lesson 3.)

Reply with your answers and I'll post the real output under each one.

Free Community Edition, if you want to run this yourself: https://synapcores.com/download?utm_source=reddit&utm_medium=owned&utm_campaign=sqlv2-lesson-5

Where does "who knows whom" live at your work today: a wiki page, an org chart, Slack history, or someone's head?


r/SQLv2 • • 20d ago

SQLv2 Lesson 4: agent memory in SQL. When a customer moves, similarity search still says "ship to Boston". REMEMBER / CURRENT / RECALL fix that (beginner)

1 Upvotes

Lesson 4 of the beginner series: one idea per post, every query run on SynapCores 2.3.2 this morning with the output pasted. (This sub is run by the SynapCores team. Plain SQL questions are welcome too.)

The problem

Your support bot keeps notes about each customer. In September, Sam said "ship to Boston". Last week Sam moved to Denver. Lessons 1-3 taught search by meaning, so let's ask the notes the bot's question:

CREATE TABLE sam_notes (id INTEGER PRIMARY KEY, noted_on TEXT, note TEXT, embedding VECTOR(384));
INSERT INTO sam_notes (id, noted_on, note) VALUES
  (1, '2026-09-02', 'Sam lives in Boston and wants orders shipped there.'),
  (2, '2026-09-02', 'Sam is allergic to wool, so never suggest wool sweaters.'),
  (3, '2026-10-28', 'Sam moved to Denver last week; ship everything to Denver from now on.');
UPDATE sam_notes SET embedding = EMBED(note);

SELECT id, noted_on, note, ROUND(COSINE_SIMILARITY(embedding, EMBED('where do we send the package')), 2) AS score
FROM sam_notes ORDER BY score DESC;

Output:

id | noted_on   | note                                                         | score
1  | 2026-09-02 | Sam lives in Boston and wants orders shipped there.          | 0.44
3  | 2026-10-28 | Sam moved to Denver last week; ship everything to Denver...  | 0.36
2  | 2026-09-02 | Sam is allergic to wool, so never suggest wool sweaters.     | 0.02

The old note wins. Similarity measures how close a note is in meaning, not whether it is still true. The Boston note talks about shipping more directly, so it scores higher, and the package goes to the wrong city.

The fix: a MEMORY that knows facts can change

A MEMORY is a built-in store for "what we know about this customer". You give each fact an attribute, and a newer value for the same attribute replaces the old one.

CREATE MEMORY shop_memory IDENTITY customer_id WITH (llm_extraction = false);

IDENTITY customer_id means every fact belongs to one customer. llm_extraction = false means we name the attribute ourselves, so no AI model has to guess it.

Step 1: REMEMBER the same three notes

REMEMBER shop_memory FOR customer_id = 42 'Sam lives in Boston and wants orders shipped there.'
  WITH (source_type = 'verified_user_statement', attribute = 'ship_city', value = 'Boston');
REMEMBER shop_memory FOR customer_id = 42 'Sam is allergic to wool, so never suggest wool sweaters.'
  WITH (source_type = 'verified_user_statement', attribute = 'allergy', value = 'wool');
REMEMBER shop_memory FOR customer_id = 42 'Sam moved to Denver last week; ship everything to Denver from now on.'
  WITH (source_type = 'verified_user_statement', attribute = 'ship_city', value = 'Denver');

The third one comes back with this in its result (trimmed to the interesting part):

"changes": {"state_changes": 1, "records_superseded": 1, "conflicts_flagged": 0}

"records_superseded: 1" means the Boston fact is now history, not current.

Step 2: CURRENT, the one answer you can act on

CURRENT shop_memory FOR customer_id = 42 ATTRIBUTE ship_city;

Output (trimmed):

"attribute": "ship_city", "value": "Denver", "confidence": 0.85,
"authority": "verified_user_statement", "valid_to": null,
"supersedes_memory_id": "mem_1m6khj7r8_rrc6od"

One value, plus where it came from and what it replaced. No ranking, no threshold to tune.

Step 3: RECALL, when you have a question instead of an attribute name

RECALL shop_memory FOR customer_id = 42 ABOUT 'where do we send the package';

The result has several parts. The two you'll use most (trimmed):

"current_state": {
  "allergy":   {"value": "wool",   "confidence": 0.85},
  "ship_city": {"value": "Denver", "confidence": 0.85}
},
"temporal": [
  {"attribute": "ship_city", "previous_value": "Boston", "current_value": "Denver"}
]

current_state is what's true now. temporal is what changed, so your bot can even say "you moved from Boston, right? Shipping to Denver." The original sentences are still in there too (under episodic), ranked by meaning like in Lessons 1-3, for when you need the exact words.

Rule of thumb

  • Similarity search (Lessons 1-3): "find the text that's about this".
  • MEMORY: "what's true about this customer right now, and what changed".

Use both: search your docs by meaning, and keep facts about people in a memory.

Homework

Sam writes: "I'm spending the winter in Miami, ship there until March."

  1. Write the REMEMBER statement.
  2. What does CURRENT ... ATTRIBUTE ship_city return now?
  3. What does the temporal part of RECALL show?

Answer in the comments and I'll reply to each one with 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-4

Before this lesson, how did you handle "the customer changed their mind": overwrite the row, keep every version, or hope for the best?


r/SQLv2 • • 24d ago

SQLv2 Lesson 3: why "I don't know" beats a confident wrong answer (pick a similarity threshold from data, beginner)

1 Upvotes

Lesson 3 of the beginner series, every query run on SynapCores 2.3.2 with real output. (This sub is run by the SynapCores team.)

The problem

Similarity search always returns a top result, even when nothing in the table answers the question. Ask a shop FAQ bot "do you sell gift cards?" and it replies with the closest thing it has. A confident wrong answer is worse than "let me get a human", so let's pick a cut-off from data.

Step 1: a small FAQ with a VECTOR column

CREATE TABLE shop_faq (id INTEGER PRIMARY KEY, question TEXT,
  answer TEXT, embedding VECTOR(384));

INSERT INTO shop_faq (id, question, answer) VALUES
(1, 'How long does shipping take?', 'Orders ship in 1-2 days and arrive in 3-5 business days.'),
(2, 'How do I return an item?', 'Start a return from Orders within 30 days; the label is free.'),
(3, 'When will I get my refund?', 'Refunds land 5-7 days after we receive the return.'),
(4, 'Do you ship internationally?', 'We ship to the US, Canada and the EU.'),
(5, 'How do I change my password?', 'Settings, then Security, then Change password.'),
(6, 'Can I cancel my order?', 'Yes, until it ships. Use Cancel on the order page.');

UPDATE shop_faq SET embedding = EMBED(question);

Step 2: the confident wrong answer

SELECT question, answer,
  COSINE_SIMILARITY(embedding, EMBED('do you sell gift cards')) AS score
FROM shop_faq ORDER BY score DESC LIMIT 1;

Do you ship internationally?  We ship to the US, Canada and the EU.  0.36

Nothing here is about gift cards, but LIMIT 1 still answers.

Step 3: score test questions you know the answer to

Ten questions: six the FAQ covers (should_match = right FAQ id), four it doesn't (NULL). Each one's best FAQ match via CROSS JOIN + ROW_NUMBER (setup and query in the first comment):

id | asked | should | faq | score
2 | how do I send an item back | 2 | 2 | 0.79
6 | stop my order please | 6 | 6 | 0.69
1 | when does my package arrive | 1 | 1 | 0.67
5 | forgot my login, how do I reset it | 5 | 5 | 0.57
4 | can you deliver to Germany | 4 | 4 | 0.56
3 | still waiting on my money back | 3 | 3 | 0.49
7 | do you sell gift cards | NULL | 4 | 0.36
10 | do you have a store in Chicago | NULL | 4 | 0.35
8 | are you hiring | NULL | 4 | 0.23
9 | is the blue jacket waterproof | NULL | 4 | 0.14

All six covered questions find the right article, even with no shared keywords ("money back" β†’ refunds). The off-topic four top out at 0.36. That gap is your threshold.

Step 4: let SQL grade each threshold

Candidate thresholds go in a table; one query counts right / wrong / "I don't know" for each (query in the first comment):

threshold | right | wrong | i_dont_know
0.00 | 6 | 4 | 0
0.30 | 6 | 2 | 2
0.40 | 6 | 0 | 4
0.45 | 6 | 0 | 4
0.50 | 5 | 0 | 5
0.60 | 3 | 0 | 7

No threshold: 4 wrong answers out of 10. At 0.40-0.45: 6 right, 0 wrong, and the off-topic four get "I don't know". At 0.60 you turn away customers you could have helped. Pick the middle of the gap: 0.45.

Step 5: the answer gate

SELECT question,
  COSINE_SIMILARITY(embedding, EMBED('how long until my refund shows up')) AS score,
  CASE WHEN COSINE_SIMILARITY(embedding, EMBED('how long until my refund shows up')) >= 0.45
    THEN answer ELSE 'Not sure yet. Passing this to a human.' END AS reply
FROM shop_faq ORDER BY score DESC LIMIT 1;

When will I get my refund?  0.84  Refunds land 5-7 days after we receive the return.

Same query with "do you sell gift cards":

Do you ship internationally?  0.36  Not sure yet. Passing this to a human.

Takeaway: similarity always has a top result. Score questions you know the answers to, let SQL grade each threshold, then gate with CASE WHEN score >= 0.45, all in the same query.

Free Community Edition (runs on a laptop): https://synapcores.com/download?utm_source=reddit&utm_medium=owned&utm_campaign=sqlv2-03

Homework: add "what are your opening hours" to test_questions (should_match NULL). What's its best score, and does 0.45 still say "I don't know"? Post your number below.

Next lesson: agent memory in SQL: REMEMBER, RECALL and CURRENT.


r/SQLv2 • • 24d ago

I Built the Same rag App Twice: 149 Lines vs 28

Thumbnail
youtube.com
1 Upvotes

r/SQLv2 • • 26d ago

SQLv2 Lesson 2: meaning + normal filters in one query (find the closest Billing article that's still current, beginner)

1 Upvotes

Lesson 2 of the beginner series: one idea per post, every query run on SynapCores 2.3.2 with the output pasted. (This sub is run by the SynapCores team. Plain SQL questions are welcome too.)

The problem

Lesson 1 found articles by meaning. Real help centers add two complications. Articles live in categories, and old articles go stale. A customer writes "I got billed two times". You want the closest Billing article that's still current, not a two-year-old page or a shipping article that happens to say "twice".

Most stacks split this across a vector store and the SQL database, then merge the results in app code. Here it's one WHERE clause.

Step 1: a table with normal columns and a VECTOR column

CREATE TABLE help_articles (
  id INTEGER PRIMARY KEY,
  category TEXT,
  updated DATE,
  question TEXT,
  embedding VECTOR(384)
);

INSERT INTO help_articles (id, category, updated, question) VALUES
  (1, 'Billing',  '2026-09-14', 'Why was I charged twice this month?'),
  (2, 'Billing',  '2024-03-02', 'Why do I see two charges on my card?'),
  (3, 'Billing',  '2026-06-30', 'How do I download an invoice?'),
  (4, 'Account',  '2026-08-11', 'I was logged out twice today'),
  (5, 'Payments', '2026-07-21', 'My card was declined at checkout'),
  (6, 'Billing',  '2026-10-02', 'How do I get a refund for a duplicate payment?'),
  (7, 'Shipping', '2026-05-19', 'My order arrived twice');

UPDATE help_articles SET embedding = EMBED(question);

EMBED() runs a small model inside the database (no API key) and stores what each question means.

Step 2: meaning only (the Lesson 1 query)

SELECT id, category, question,
       COSINE_SIMILARITY(embedding, EMBED('I got billed two times')) AS score
FROM help_articles ORDER BY score DESC LIMIT 4;

1  Billing   Why was I charged twice this month?               0.70
7  Shipping  My order arrived twice                            0.59
2  Billing   Why do I see two charges on my card?              0.54
6  Billing   How do I get a refund for a duplicate payment?    0.48

The top hit is right, but #2 is a shipping article and #3 is from 2024. Meaning alone doesn't know your business rules.

Step 3: meaning + normal filters, one query

SELECT id, updated, question,
       COSINE_SIMILARITY(embedding, EMBED('I got billed two times')) AS score
FROM help_articles
WHERE category = 'Billing' AND updated >= '2026-01-01'
ORDER BY score DESC LIMIT 3;

1  2026-09-14  Why was I charged twice this month?               0.70
6  2026-10-02  How do I get a refund for a duplicate payment?    0.48
3  2026-06-30  How do I download an invoice?                     0.32

The WHERE drops the wrong category and the stale article. ORDER BY score ranks what's left by meaning. Same statement, same database, nothing to merge.

Step 4: add a threshold so weak matches don't show up

SELECT id, question,
       COSINE_SIMILARITY(embedding, EMBED('I got billed two times')) AS score
FROM help_articles
WHERE category = 'Billing' AND updated >= '2026-01-01'
  AND COSINE_SIMILARITY(embedding, EMBED('I got billed two times')) > 0.5
ORDER BY score DESC;

1  Why was I charged twice this month?   0.70

The invoice article (0.32) no longer pads out the list. One confident answer beats three guesses.

Bonus: meaning inside GROUP BY

Which categories does this complaint touch?

SELECT category, COUNT(*) AS matches FROM help_articles
WHERE COSINE_SIMILARITY(embedding, EMBED('I got billed two times')) > 0.4
GROUP BY category ORDER BY matches DESC;

Billing   3
Shipping  1
Account   1

Run that over a day of support tickets instead of articles and you have a "what are people complaining about" report.

What you just learned

  • Similarity is just another expression, so it goes anywhere SQL expressions go: SELECT, WHERE, ORDER BY, GROUP BY.
  • Filters (category, updated) handle the business rules. COSINE_SIMILARITY handles meaning.
  • A threshold in the WHERE drops weak matches entirely.

Free Community Edition (runs on a laptop): https://synapcores.com/download?utm_source=reddit&utm_medium=owned&utm_campaign=sqlv2-02

Homework: change step 3 to search the Payments category for "the shop refused my card". What score does the top result get? Post it below.

Next lesson: why "I don't know" beats a confident wrong answer, and how to pick the threshold.


r/SQLv2 • • Oct 23 '26

SQLv2 Lesson 1: search by meaning, not keywords (semantic search in 5 SQL statements, beginner)

1 Upvotes

Welcome to the first lesson of a beginner series: one idea per post, every query tested on SynapCores 2.3.1, copy-paste ready. (This sub is run by the SynapCores team. Questions about plain SQL are welcome too.)

The problem

A customer types "my internet connection drops every few minutes." Your help center has an article called "My Wi-Fi keeps disconnecting." A keyword search finds nothing, because the two sentences share no words. Semantic search compares meaning instead.

What you need: SynapCores Community Edition (free, runs on a laptop; one-line installer at synapcores.com/download), and the Query Editor that opens in your browser. No API keys and no external AI service.

Step 1: a table with a VECTOR column

CREATE TABLE help_articles (
  id INTEGER PRIMARY KEY,
  question TEXT,
  answer TEXT,
  embedding VECTOR(384)
);

A VECTOR(384) holds 384 numbers that describe what a piece of text means. Similar meanings get similar numbers.

Step 2: add some articles

INSERT INTO help_articles (id, question, answer) VALUES
  (1, 'How do I reset my password?', 'Use "Forgot password" on the login page.'),
  (2, 'My Wi-Fi keeps disconnecting', 'Move the router away from the microwave and update its firmware.'),
  (3, 'How can I change my billing address?', 'Settings > Billing > Edit address.'),
  (4, 'The app crashes when I open it', 'Update to the latest version, then clear the app cache.'),
  (5, 'Can I export my data to CSV?', 'Yes: Reports > Export > CSV.'),
  (6, 'How do I cancel my subscription?', 'Settings > Plan > Cancel. You keep access until the period ends.');

Step 3: let the database compute the meanings

UPDATE help_articles SET embedding = EMBED(question);

EMBED() runs a small embedding model inside the database and turns each question into a vector. Six rows updated.

Step 4: keyword search fails...

SELECT id, question FROM help_articles WHERE question LIKE '%internet%';

(0 rows)

Step 5: ...meaning search works

SELECT question,
       COSINE_SIMILARITY(embedding, EMBED('my internet connection drops every few minutes')) AS score
FROM help_articles ORDER BY score DESC LIMIT 3;

My Wi-Fi keeps disconnecting           0.56
The app crashes when I open it         0.26
How can I change my billing address?   0.15

COSINE_SIMILARITY scores how close two meanings are (1.0 means identical). The right article wins by a wide margin, without sharing a single word with the question.

One more, phrased the way real people write:

SELECT question,
       COSINE_SIMILARITY(embedding, EMBED('I want to stop paying for this')) AS score
FROM help_articles ORDER BY score DESC LIMIT 3;

How do I cancel my subscription?       0.59
How can I change my billing address?   0.31
How do I reset my password?            0.16

Bonus: a threshold instead of top-N

SELECT question, answer FROM help_articles
WHERE COSINE_SIMILARITY(embedding, EMBED('forgot my login')) > 0.5;

How do I reset my password? | Use "Forgot password" on the login page.

A threshold lets you say "I don't know" when nothing is close enough, instead of always returning something. (Lesson 3 is about why that matters for AI answers.)

What you just learned

  • VECTOR(n) is a column type for meanings.
  • EMBED(text) creates the vector, inside the database.
  • COSINE_SIMILARITY(a, b) compares two meanings.
  • ORDER BY score DESC LIMIT k gives the top-k most similar rows.

Try it yourself: add an article "How do I update the router firmware?", then search for "my router is out of date". Post your top score below.

Next lesson: combining meaning with normal filters, e.g. "articles similar to X, but only in the Billing category, updated this year", in one query.


r/SQLv2 • • Jan 21 '26

Image OCR Extraction

1 Upvotes

Images with text β€” receipts, business cards, documents, screenshots β€” are unsearchable by default. EXTRACT_TEXT runs OCR and stores the result. Now you can search image content with SQL.

What this solves:

  • Searching within scanned documents
  • Receipt text extraction for expense tracking
  • Business card contact extraction
  • Screenshot error message searching

Images with extracted text:

CREATE TABLE images_with_text (

id INTEGER PRIMARY KEY,

filename VARCHAR(255) NOT NULL,

image IMAGE(JPEG),

image_type VARCHAR(50),

extracted_text TEXT,

processed_at TIMESTAMP,

created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP

);

-- Extract text from images

UPDATE images_with_text

SET extracted_text = EXTRACT_TEXT(image),

processed_at = CURRENT_TIMESTAMP

WHERE image IS NOT NULL;

Receipt scanner:

CREATE TABLE receipt_scans (

id INTEGER PRIMARY KEY,

receipt_image IMAGE(JPEG),

store_name VARCHAR(255),

receipt_text TEXT,

total_amount DECIMAL(10, 2),

receipt_date DATE,

expense_category VARCHAR(50),

scanned_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP

);

-- Process receipts

UPDATE receipt_scans

SET receipt_text = EXTRACT_TEXT(receipt_image)

WHERE receipt_image IS NOT NULL;

-- Search receipts

SELECT store_name, total_amount, receipt_date

FROM receipt_scans

WHERE receipt_text LIKE '%office supplies%';

Why this works: EXTRACT_TEXT runs OCR on IMAGE columns. Extracted text is stored for searching without re-processing. Standard SQL LIKE or full-text search on the result. Processing status tracks what's been done.

Image TypeUse Case
Business CardsContact extraction
ReceiptsExpense tracking
DocumentsFull-text search
ScreenshotsError log capture

Full recipe with document indexing: https://synapcores.com/sqlv2

Create a free account to test OCR extraction.

Questions on OCR accuracy β€” drop them below.


r/SQLv2 • • Jan 21 '26

JSON and JSONB Columns

1 Upvotes

Rigid schemas break when requirements change. Adding columns requires migrations. JSON columns provide flexibility where you need it while keeping structure where you don't.

What this solves:

  • Metadata that varies between records
  • Configuration storage without dedicated tables
  • Event data with varying payloads
  • Audit logs with before/after snapshots

Product metadata with JSON:

CREATE TABLE products (

id INTEGER PRIMARY KEY,

name VARCHAR(255) NOT NULL,

base_price DECIMAL(10, 2) NOT NULL,

metadata JSON,

created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP

);

INSERT INTO products (id, name, base_price, metadata) VALUES

(1, 'Laptop Pro', 1299.99,

'{"brand": "TechCo", "specs": {"cpu": "Intel i7", "ram": "16GB"}, "colors": ["silver", "black"]}'),

(2, 'Wireless Mouse', 49.99,

'{"brand": "ClickMaster", "specs": {"dpi": 1600, "buttons": 6}, "colors": ["black", "white"]}');

Audit log pattern:

CREATE TABLE audit_log (

id INTEGER PRIMARY KEY,

table_name VARCHAR(100) NOT NULL,

record_id INTEGER NOT NULL,

action VARCHAR(20) NOT NULL,

old_values JSON,

new_values JSON,

changed_by VARCHAR(100),

changed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP

);

INSERT INTO audit_log (id, table_name, record_id, action, old_values, new_values, changed_by) VALUES

(1, 'products', 1, 'UPDATE',

'{"base_price": 1199.99}',

'{"base_price": 1299.99}',

'admin@example.com');

Why this works: JSON stores varying structures per row. JSONB (binary JSON) optimizes for querying. Nested objects and arrays supported. Schema stays simple, flexibility where needed.

FeatureJSONJSONB
StorageTextBinary
Key orderPreservedNot preserved
Best forLoggingQuerying

Full recipe with configuration patterns: https://synapcores.com/sqlv2

Sign up to test JSON queries directly.

Questions on JSON vs JSONB β€” drop them below.


r/SQLv2 • • Jan 12 '26

JSON columns in SQL: flexible metadata without schema migrations β€” practical patterns

1 Upvotes

Rigid schemas break when requirements change. Adding columns requires migrations. JSON columns provide flexibility where you need it while keeping structure where you don't.

What this solves:

  • Metadata that varies between records
  • Configuration storage without dedicated tables
  • Event data with varying payloads
  • Audit logs with before/after snapshots

Product metadata with JSON:

CREATE TABLE products (
    id INTEGER PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    base_price DECIMAL(10, 2) NOT NULL,
    metadata JSON,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

INSERT INTO products (id, name, base_price, metadata) VALUES
(1, 'Laptop Pro', 1299.99,
    '{"brand": "TechCo", "specs": {"cpu": "Intel i7", "ram": "16GB"}, "colors": ["silver", "black"]}'),
(2, 'Wireless Mouse', 49.99,
    '{"brand": "ClickMaster", "specs": {"dpi": 1600, "buttons": 6}, "colors": ["black", "white"]}');

Audit log pattern:

CREATE TABLE audit_log (
    id INTEGER PRIMARY KEY,
    table_name VARCHAR(100) NOT NULL,
    record_id INTEGER NOT NULL,
    action VARCHAR(20) NOT NULL,
    old_values JSON,
    new_values JSON,
    changed_by VARCHAR(100),
    changed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

INSERT INTO audit_log (id, table_name, record_id, action, old_values, new_values, changed_by) VALUES
(1, 'products', 1, 'UPDATE',
    '{"base_price": 1199.99}',
    '{"base_price": 1299.99}',
    'admin@example.com');

Why this works: JSON stores varying structures per row. JSONB (binary JSON) optimizes for querying. Nested objects and arrays supported. Schema stays simple, flexibility where needed.

FeatureJSONJSONB
StorageTextBinary
Key orderPreservedNot preserved
Best forLoggingQuerying

Full recipe with configuration patterns: https://synapcores.com/sqlv2

Sign up to test JSON queries directly.

Questions on JSON vs JSONB β€” drop them below.


r/SQLv2 • • Jan 10 '26

VECTOR columns for embeddings in SQL β€” semantic search without a separate vector DB

1 Upvotes

Building semantic search typically means running a separate vector database alongside your SQL database. Data lives in two places, sync becomes a problem, and queries span two systems. Here's the unified approach.

What this solves:

  • No separate vector database to maintain
  • Embeddings live with the data they describe
  • One query language for structured + semantic search

AIDB's VECTOR type stores embeddings directly. EMBED() generates them from text. Same SQL you already know.

Table with vector column:

CREATE TABLE product_embeddings (
    id INTEGER PRIMARY KEY,
    product_name VARCHAR(255) NOT NULL,
    description TEXT,
    embedding VECTOR(384),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Generate embeddings:

-- Insert products
INSERT INTO product_embeddings (id, product_name, description) VALUES
    (1, 'Wireless Headphones', 'Premium noise-canceling with 30-hour battery'),
    (2, 'Bluetooth Speaker', 'Portable waterproof with 360-degree sound');

-- Generate embeddings from descriptions
UPDATE product_embeddings
SET embedding = EMBED(description)
WHERE embedding IS NULL;

Why this works: VECTOR(384) stores 384-dimensional embeddings (MiniLM). VECTOR(768) for BERT Base. VECTOR(1536) for OpenAI-compatible. EMBED() converts text to vectors inline. No external API calls in application code.

ModelDimensionsUse Case
MiniLM384General-purpose, fast
BERT Base768High-quality semantic search
BERT Large1024Maximum quality

Full recipe with similarity search examples: https://synapcores.com/sqlv2

Sign up to get a test environment and run vector queries.

Questions on embedding dimensions or model selection β€” drop them below.


r/SQLv2 • • Jan 10 '26

Native AUDIO, VIDEO, IMAGE, PDF columns in SQL β€” no blob workarounds needed

1 Upvotes

Storing multimedia in databases typically means BLOB columns with external format validation, or worse β€” storing file paths and managing a separate file system. Here's how native multimedia types change that.

What this solves:

  • No more generic BLOB columns with manual format tracking
  • No external file storage with URL reference management
  • Format enforcement at the schema level, not application code

AIDB supports IMAGE, AUDIO, VIDEO, and PDF as first-class column types with explicit format declarations.

Multimedia table with format types:

CREATE TABLE multimedia_content (
    id INTEGER PRIMARY KEY,
    title VARCHAR(255) NOT NULL,
    photo IMAGE(JPEG),
    screenshot IMAGE(PNG),
    music_track AUDIO(MP3),
    voice_memo AUDIO(WAV),
    video_clip VIDEO(MP4),
    document PDF,
    uploaded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Format-specific tables:

CREATE TABLE video_library (
    id INTEGER PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    mp4_file VIDEO(MP4),
    webm_file VIDEO(WEBM),
    mov_file VIDEO(MOV),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Why this works: Format is declared at schema level β€” IMAGE(JPEG) vs IMAGE(PNG). The database enforces format consistency. Queries work on multimedia tables the same as any other table. No special handling code required.

TypeSupported Formats
IMAGEJPEG, PNG, WEBP, GIF, BMP
AUDIOMP3, WAV, FLAC, AAC, OGG
VIDEOMP4, AVI, MKV, WEBM, MOV
PDFPDF documents

Full recipe with all format examples: https://synapcores.com/sqlv2

Create a free account to test multimedia queries directly.

Happy to go deeper on any format handling.


r/SQLv2 • • Jan 09 '26

SQL data types reference: INTEGER to UUID in one table β€” schema + examples

1 Upvotes

Every database project eventually asks "what's the right data type for this column?" Here's a reference table demonstrating all standard SQL types in AIDB with working examples.

What this covers:

  • Numeric types: SMALLINT, INTEGER, BIGINT, DECIMAL, REAL, DOUBLE
  • Text types: CHAR, VARCHAR, TEXT
  • Date/Time types: DATE, TIME, TIMESTAMP
  • Special types: BOOLEAN, UUID, BYTEA

One table, all types, with sample data showing proper formatting.

Comprehensive data types table:

CREATE TABLE data_types_demo (
    id INTEGER PRIMARY KEY,
    is_active BOOLEAN DEFAULT TRUE,
    small_number SMALLINT,
    regular_number INTEGER,
    big_number BIGINT,
    decimal_value DECIMAL(10, 2),
    float_value REAL,
    double_value DOUBLE,
    fixed_text CHAR(10),
    variable_text VARCHAR(255),
    long_text TEXT,
    unique_id UUID,
    birth_date DATE,
    start_time TIME,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Type-appropriate queries:

-- Numeric precision maintained
SELECT id, decimal_value FROM data_types_demo WHERE decimal_value > 100.00;

-- Date comparisons work naturally
SELECT id, birth_date FROM data_types_demo WHERE birth_date > '1995-01-01';

-- Aggregations respect types
SELECT SUM(decimal_value), AVG(float_value), MAX(big_number) FROM data_types_demo;

Why this matters: Choosing the right type affects storage efficiency, query performance, and data integrity. DECIMAL preserves precision for financial data. UUID handles distributed systems. BIGINT stores values up to 9 quintillion.

Full recipe with all examples: https://synapcores.com/sqlv2

Sign up to get a test environment where you can run these queries against real data.

Interested in feedback on type selection patterns.


r/SQLv2 • • Jan 08 '26

SQL basics in AIDB: Your first table in 5 minutes β€” schema + queries

1 Upvotes

Getting started with a new database shouldn't require reading 50 pages of documentation. Here's a minimal working example that covers CREATE, INSERT, SELECT, UPDATE β€” the operations you'll use 90% of the time.

What this covers:

  • Creating a table with common data types (INTEGER, VARCHAR, TEXT, TIMESTAMP)
  • PRIMARY KEY and DEFAULT constraints
  • Basic CRUD operations in one place

This is the "hello world" for AIDB. 4 columns, 3 records, all the fundamentals.

The table:

CREATE TABLE hello_world (
    id INTEGER PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    message TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Insert and query:

INSERT INTO hello_world (id, name, message) VALUES
    (1, 'Alice', 'Hello from AIDB!'),
    (2, 'Bob', 'Welcome to the database'),
    (3, 'Charlie', 'SQL is fun!');

SELECT * FROM hello_world;

Why this works: DEFAULT CURRENT_TIMESTAMP auto-populates the timestamp on insert. PRIMARY KEY ensures unique row identification. NOT NULL enforces that required fields always have values.

Full recipe with all operations (UPDATE, WHERE clauses, cleanup): https://synapcores.com/sqlv2

Create a free account to spin up a test environment and run queries directly.

Questions on syntax or data types β€” drop them below.


r/SQLv2 • • Jan 08 '26

We are almost there!!!! Keep coming back...

1 Upvotes

r/SQLv2 • • Dec 04 '25

We built SQLv2 from scratch. Here’s why we refused to bolt ML on top of SQL.

1 Upvotes

Every AI-database project I reviewed had the same flaw:
ML was treated as an add-on, not a core function.

Frameworks kept stacking layers β€” APIs for inference, pipelines for embeddings, external services for vector search.
Each new layer added latency, cost, and fragility.

I didn’t want a patchwork. I wanted a unified engine.

So I built SQLv2 β€” an open standard that merges:
β€’ SQL for structured data
β€’ Vector operations for similarity search
β€’ ML inference and generative functions β€” all in-engine

No external APIs. No data movement. No latency tax.

The result: one database that handles both analytics and prediction.
A true AI-Native SQL layer where intelligence lives next to the data, not above it.

We implemented this in SynapCores, delivering 20–100Γ— faster AI workloads and cutting inference costs by up to 90%.

If you’ve ever struggled to make SQL and ML coexist cleanly, this standard was built for you.

πŸ‘‰ Join the discussion: SynapCores SQLv2


r/SQLv2 • • Dec 04 '25

What is SQLv2

Post image
1 Upvotes

r/SQLv2 • • Nov 01 '25

Why Your Database Can't Actually See Your Users (And What That's Really Costing You)

Thumbnail
devops7.com
1 Upvotes

r/SQLv2 • • Oct 15 '25

How to predict E-commerce/Amazon sales volume

1 Upvotes

In this video we follow step by step a ML recipe to train time series of sales volumes for a fictitious amazon Store, the model is trained with basic features and we achieve a 57% accuracy levels. In the follow up, will record a new video showing how to do feature engineering to improve the accuracy of the model.


r/SQLv2 • • Oct 14 '25

A Complete Guide to SYNAPCORES SQLv2 Data Types and Creating Tables

1 Upvotes

πŸš€ A Complete Guide to SYNAPCORES SQLv2 Data Types and Creating Tables

Hey everyone! I've been working with SYNAPCORES SQLv2 for a while now, and I wanted to share a comprehensive guide on data types and table creation. This database is pretty unique because it combines traditional SQL with AI-native capabilities, so buckle up!

πŸ“Š Standard Data Types

SYNAPCORES supports all the SQL data types you'd expect, plus some exciting AI-specific ones. Let's break them down:

Numeric Types

  • BOOLEAN - True/false values
  • SMALLINT - 16-bit signed integer (-32,768 to 32,767)
  • INTEGER - 32-bit signed integer
  • BIGINT - 64-bit signed integer (for those really big numbers)
  • REAL - 32-bit floating point
  • DOUBLE - 64-bit floating point (more precision)
  • DECIMAL(p, s) - Fixed-point decimal (p = precision, s = scale)

String Types

  • TEXT - Variable-length text (unlimited)
  • VARCHAR(n) - Variable character with max length n
  • CHAR(n) - Fixed-length character (always n characters)

Binary & Structured Data

  • BYTEA - Binary data
  • JSON - JSON documents (stored as text)
  • JSONB - Binary JSON (faster queries, optimized storage)
  • UUID - Universal Unique Identifiers

Date & Time Types

  • TIMESTAMP - Date and time together
  • DATE - Date only (no time component)
  • TIME - Time only (no date component)

πŸ€– AI-Native Data Types (This is where it gets cool!)

Here's what makes SYNAPCORES really special:

  • VECTOR(n) - Dense vectors for embeddings (n = dimensions)
  • AUDIO - Audio file storage
  • VIDEO - Video file storage
  • IMAGE - Image file storage
  • PDF - PDF document storage

These types are perfect for ML workloads, RAG systems, and multimedia applications!

πŸ› οΈ Creating Tables: The Basics

Here's the basic syntax:

CREATE TABLE [IF NOT EXISTS] table_name (
    column_name data_type [column_constraint],
    ...
    [table_constraint]
);

Simple Example: A Users Table

CREATE TABLE users (
    id INTEGER PRIMARY KEY,
    username VARCHAR(50) NOT NULL UNIQUE,
    email VARCHAR(255) NOT NULL UNIQUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    is_active BOOLEAN DEFAULT true
);

πŸ” Column Constraints

You can add constraints to individual columns:

  • PRIMARY KEY - Unique identifier for the row
  • UNIQUE - No duplicate values allowed
  • NOT NULL - Value must be provided
  • CHECK (expression) - Custom validation rule
  • DEFAULT expression - Default value if none provided
  • REFERENCES foreign_table (foreign_column) - Foreign key

Example with Multiple Constraints

CREATE TABLE products (
    product_id INTEGER PRIMARY KEY,
    product_name VARCHAR(100) NOT NULL,
    price DECIMAL(10, 2) NOT NULL CHECK (price > 0),
    stock_quantity INTEGER DEFAULT 0 CHECK (stock_quantity >= 0),
    category VARCHAR(50) NOT NULL,
    created_date DATE DEFAULT CURRENT_DATE
);

πŸ”— Table-Level Constraints

For more complex constraints, use table-level constraints:

CREATE TABLE orders (
    order_id INTEGER PRIMARY KEY,
    customer_id INTEGER NOT NULL,
    product_id INTEGER NOT NULL,
    quantity INTEGER NOT NULL CHECK (quantity > 0),
    order_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    total_amount DECIMAL(12, 2) NOT NULL,
    
    -- Table constraints
    FOREIGN KEY (customer_id) REFERENCES users (id),
    FOREIGN KEY (product_id) REFERENCES products (product_id),
    CHECK (total_amount >= 0)
);

🎯 Real-World Example: E-Commerce Schema

Here's a complete example with multiple related tables:

-- Customers table
CREATE TABLE customers (
    customer_id INTEGER PRIMARY KEY,
    first_name VARCHAR(50) NOT NULL,
    last_name VARCHAR(50) NOT NULL,
    email VARCHAR(255) NOT NULL UNIQUE,
    phone VARCHAR(20),
    registration_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Products table with JSON metadata
CREATE TABLE products (
    product_id INTEGER PRIMARY KEY,
    name VARCHAR(200) NOT NULL,
    description TEXT,
    price DECIMAL(10, 2) NOT NULL CHECK (price >= 0),
    inventory_count INTEGER DEFAULT 0 CHECK (inventory_count >= 0),
    category VARCHAR(50) NOT NULL,
    metadata JSONB,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Orders table
CREATE TABLE orders (
    order_id INTEGER PRIMARY KEY,
    customer_id INTEGER NOT NULL,
    order_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    status VARCHAR(20) DEFAULT 'pending',
    total_amount DECIMAL(12, 2) NOT NULL CHECK (total_amount >= 0),
    
    FOREIGN KEY (customer_id) REFERENCES customers (customer_id),
    CHECK (status IN ('pending', 'processing', 'shipped', 'delivered', 'cancelled'))
);

-- Order items table
CREATE TABLE order_items (
    item_id INTEGER PRIMARY KEY,
    order_id INTEGER NOT NULL,
    product_id INTEGER NOT NULL,
    quantity INTEGER NOT NULL CHECK (quantity > 0),
    unit_price DECIMAL(10, 2) NOT NULL,
    subtotal DECIMAL(12, 2) NOT NULL,
    
    FOREIGN KEY (order_id) REFERENCES orders (order_id),
    FOREIGN KEY (product_id) REFERENCES products (product_id)
);

πŸš€ AI-Powered Tables Example

Now for the fun part - using those AI-native types!

-- Product catalog with images and embeddings
CREATE TABLE product_catalog (
    product_id INTEGER PRIMARY KEY,
    product_name VARCHAR(200) NOT NULL,
    description TEXT,
    product_image IMAGE,
    description_embedding VECTOR(768),
    price DECIMAL(10, 2) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Document repository with PDFs
CREATE TABLE documents (
    doc_id INTEGER PRIMARY KEY,
    title VARCHAR(255) NOT NULL,
    document_file PDF,
    document_embedding VECTOR(1536),
    upload_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    category VARCHAR(50)
);

-- Media library
CREATE TABLE media_library (
    media_id INTEGER PRIMARY KEY,
    title VARCHAR(255) NOT NULL,
    media_type VARCHAR(20) NOT NULL,
    audio_file AUDIO,
    video_file VIDEO,
    thumbnail IMAGE,
    duration_seconds INTEGER,
    uploaded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    
    CHECK (media_type IN ('audio', 'video', 'mixed'))
);

πŸ’‘ Pro Tips

  1. Use IF NOT EXISTS to make your scripts idempotent:
  2. Always define PRIMARY KEYS for better query performance
  3. Use CHECK constraints to enforce business rules at the database level
  4. JSONB over JSON when you need to query JSON fields frequently
  5. Foreign keys maintain referential integrity automatically
  6. DEFAULT values reduce application logic and ensure consistency

πŸŽ“ Complex Composite Primary Key Example

CREATE TABLE user_permissions (
    user_id INTEGER NOT NULL,
    resource_id INTEGER NOT NULL,
    permission_type VARCHAR(50) NOT NULL,
    granted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    granted_by INTEGER,
    
    PRIMARY KEY (user_id, resource_id, permission_type),
    FOREIGN KEY (user_id) REFERENCES users (id),
    FOREIGN KEY (granted_by) REFERENCES users (id),
    CHECK (permission_type IN ('read', 'write', 'delete', 'admin'))
);

πŸ” Table with UUID as Primary Key

CREATE TABLE sessions (
    session_id UUID PRIMARY KEY,
    user_id INTEGER NOT NULL,
    ip_address VARCHAR(45),
    user_agent TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    expires_at TIMESTAMP NOT NULL,
    is_active BOOLEAN DEFAULT true,
    
    FOREIGN KEY (user_id) REFERENCES users (id)
);

πŸ“ Best Practices Checklist

βœ… Always define primary keys
βœ… Use NOT NULL for required fields
βœ… Add CHECK constraints for data validation
βœ… Use appropriate data types (don't use TEXT for everything!)
βœ… Name your constraints explicitly when possible
βœ… Consider foreign keys for referential integrity
βœ… Use UNIQUE constraints to prevent duplicates
βœ… Add DEFAULT values for optional fields
βœ… Use JSONB for flexible schema parts
βœ… Use VECTOR types for ML/AI features

πŸ€” Common Pitfalls to Avoid

❌ Using TEXT when VARCHAR(n) would be better
❌ Forgetting NOT NULL on important fields
❌ Not using foreign keys (leads to orphaned records)
❌ Over-normalizing (sometimes JSON is okay!)
❌ Not planning for future schema changes
❌ Using wrong numeric types (INTEGER vs BIGINT)
❌ Forgetting to add indexes on foreign keys

🎬 Full Example: Blog Platform Schema

Here's everything together in a realistic scenario:

-- Users table
CREATE TABLE IF NOT EXISTS users (
    user_id INTEGER PRIMARY KEY,
    username VARCHAR(50) NOT NULL UNIQUE,
    email VARCHAR(255) NOT NULL UNIQUE,
    password_hash VARCHAR(255) NOT NULL,
    full_name VARCHAR(100),
    bio TEXT,
    profile_image IMAGE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    last_login TIMESTAMP,
    is_verified BOOLEAN DEFAULT false,
    is_active BOOLEAN DEFAULT true,
    
    CHECK (email LIKE '%@%.%')
);

-- Blog posts table
CREATE TABLE IF NOT EXISTS posts (
    post_id INTEGER PRIMARY KEY,
    author_id INTEGER NOT NULL,
    title VARCHAR(255) NOT NULL,
    slug VARCHAR(255) NOT NULL UNIQUE,
    content TEXT NOT NULL,
    excerpt VARCHAR(500),
    featured_image IMAGE,
    content_embedding VECTOR(768),
    status VARCHAR(20) DEFAULT 'draft',
    published_at TIMESTAMP,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    view_count INTEGER DEFAULT 0,
    metadata JSONB,
    
    FOREIGN KEY (author_id) REFERENCES users (user_id),
    CHECK (status IN ('draft', 'published', 'archived')),
    CHECK (view_count >= 0)
);

-- Comments table
CREATE TABLE IF NOT EXISTS comments (
    comment_id INTEGER PRIMARY KEY,
    post_id INTEGER NOT NULL,
    user_id INTEGER NOT NULL,
    parent_comment_id INTEGER,
    content TEXT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP,
    is_deleted BOOLEAN DEFAULT false,
    
    FOREIGN KEY (post_id) REFERENCES posts (post_id),
    FOREIGN KEY (user_id) REFERENCES users (user_id),
    FOREIGN KEY (parent_comment_id) REFERENCES comments (comment_id)
);

-- Tags table
CREATE TABLE IF NOT EXISTS tags (
    tag_id INTEGER PRIMARY KEY,
    tag_name VARCHAR(50) NOT NULL UNIQUE,
    slug VARCHAR(50) NOT NULL UNIQUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Post tags junction table
CREATE TABLE IF NOT EXISTS post_tags (
    post_id INTEGER NOT NULL,
    tag_id INTEGER NOT NULL,
    
    PRIMARY KEY (post_id, tag_id),
    FOREIGN KEY (post_id) REFERENCES posts (post_id),
    FOREIGN KEY (tag_id) REFERENCES tags (tag_id)
);

-- Likes table
CREATE TABLE IF NOT EXISTS likes (
    user_id INTEGER NOT NULL,
    post_id INTEGER NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    
    PRIMARY KEY (user_id, post_id),
    FOREIGN KEY (user_id) REFERENCES users (user_id),
    FOREIGN KEY (post_id) REFERENCES posts (post_id)
);

πŸŽ‰ Conclusion

SYNAPCORES SQLv2 gives you the power of traditional SQL plus modern AI capabilities. The key is understanding your data types and using constraints effectively. Start simple, then add AI features when you need them!

Questions? Drop them in the comments! Happy coding! πŸš€

Note: Remember to check the official SYNAPCORES documentation for the latest features and updates!

https://synapcores.com/sqlv2