Live build, 12–13 Dec: turn an app agentic, no fee. Register →

Why RAG If You Already Have a Database? Explained Simply 🔎

Published

From the course: Agentic AI from Scratch (Python), session 15: How RAG works: retrieve, add to the prompt, generate

Your company already keeps its HR policies in a database. An employee types: “Can I carry over my unused holidays to next year?” The answer is sitting right there in a table, and the search box still returns nothing useful.

This post explains why that happens, what RAG (Retrieval-Augmented Generation) adds on top of your database, and when you don’t need it at all. You’ll see a small before-and-after in Python.

TL;DR 📌

  1. A database finds what you ask for exactly. It matches words, numbers and IDs. It doesn’t know what a sentence means.
  2. People ask in their own words, which are often different from the words in your documents.
  3. RAG adds two things: a search that matches by meaning, and an LLM that reads the found text and writes a plain answer.
  4. RAG still uses a database. It doesn’t replace yours; it reads from it in a smarter way.
  5. For counts, totals and exact lookups, plain SQL is still the right tool.

The idea in plain words 💡

A database is a very fast, very literal librarian. Ask for the book with ID 4021 and you get it instantly. Ask for “rows where the text contains carry over” and it checks every row for those exact letters. If the policy says “rolled forward” instead, the librarian shrugs. It isn’t being lazy; it was never built to understand language.

Here is our running example. The table holds four policy lines:

id text
1 Up to 5 days of unused annual leave may be rolled forward into the next calendar year.
2 The office is closed on public holidays listed in the yearly calendar.
3 Sick leave requires a doctor’s note after 3 consecutive days.
4 Employees can work from home up to 2 days per week with manager approval.

The employee says “carry over” and “holidays”. The policy says “rolled forward” and “annual leave”. Same meaning, zero shared words. Worse, the word “holidays” does appear, but in the wrong row (public holidays).

You might say: “Postgres has full-text search.” It helps. Postgres can reduce words to a base form, so rats matches rat, and it can rank results by relevance. But matching “carry over” to “rolled forward” needs a synonym dictionary that someone writes and maintains by hand. Nobody can list every way a person might phrase a question.

That gap is what RAG fills. Three terms first:

  • Embedding: a list of numbers that represents the meaning of a piece of text. Texts with similar meaning get similar numbers, even when the words differ.
  • Similarity search: comparing those number lists to find the closest ones. A common measure is cosine similarity: a score where higher means “closer in meaning”.
  • LLM (large language model): a model like Claude or GPT that reads text and writes text.

RAG = Retrieve the most relevant text by meaning, Augment (add) it to the question, and let the LLM Generate an answer from it. The idea was introduced in a 2020 paper by Lewis and colleagues at Facebook AI Research. Their main point still holds: a model’s built-in knowledge is hard to update and hard to check, while text you fetch from a store can be updated any time and shown as evidence.

Notice the database is still there on the left. RAG changes how you search it and adds a reader at the end. Notice the database is still there on the left. RAG changes how you search it and adds a reader at the end.

Step by step 🛠️

Store: save the text and its meaning

You keep your policy lines as before. Next to each one, you also save its embedding. This happens once, when a policy is added or changed, not on every question. The numbers can live in a dedicated vector database or in the database you already run (Postgres with the pgvector extension, for example).

Retrieve: search by meaning, not by letters

When a question arrives, you turn it into an embedding using the same model, then pick the stored lines whose numbers are closest. “Carry over my unused holidays” lands near “unused annual leave rolled forward”, because the model learned from huge amounts of text that these phrases are used the same way.

Generate: let the LLM write the answer

The retrieved lines still aren’t an answer; they’re evidence. You pass them to an LLM with an instruction like “answer using only this text, and say you don’t know if it isn’t covered.” The employee gets: “Yes, up to 5 days of unused annual leave can roll into next year.”

The code: before and after 🧑‍💻

Before: plain SQL. This runs as-is with Python’s built-in sqlite3.

import sqlite3

db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE policy (id INTEGER, text TEXT)")
db.executemany("INSERT INTO policy VALUES (?, ?)", [
    (1, "Up to 5 days of unused annual leave may be rolled forward into the next calendar year."),
    (2, "The office is closed on public holidays listed in the yearly calendar."),
    (3, "Sick leave requires a doctor's note after 3 consecutive days."),
    (4, "Employees can work from home up to 2 days per week with manager approval."),
])

for word in ["carry over", "holidays"]:
    rows = db.execute("SELECT id, text FROM policy WHERE text LIKE ?", (f"%{word}%",)).fetchall()
    print(f"LIKE '%{word}%' ->", rows)

Output:

LIKE '%carry over%' -> []
LIKE '%holidays%' -> [(2, 'The office is closed on public holidays listed in the yearly calendar.')]

One search finds nothing. The other finds the wrong policy. The database did exactly what it was told.

After: RAG. It uses sentence-transformers for free local embeddings and the Anthropic SDK for the LLM (you need an ANTHROPIC_API_KEY).

# pip install sentence-transformers anthropic
from sentence_transformers import SentenceTransformer
import anthropic

policies = [
    "Up to 5 days of unused annual leave may be rolled forward into the next calendar year.",
    "The office is closed on public holidays listed in the yearly calendar.",
    "Sick leave requires a doctor's note after 3 consecutive days.",
    "Employees can work from home up to 2 days per week with manager approval.",
]

# 1. Store: turn every policy line into an embedding, once.
model = SentenceTransformer("all-MiniLM-L6-v2")   # small, free, runs on a laptop
policy_vectors = model.encode(policies)

# 2. Retrieve: embed the question and find the closest policies by meaning.
question = "Can I carry over my unused holidays to next year?"
question_vector = model.encode([question])
scores = model.similarity(question_vector, policy_vectors)[0]   # cosine similarity
top = scores.argsort(descending=True)[:2]
context = "\n".join(policies[i] for i in top)
for i in top:
    print(f"{float(scores[i]):.2f}  {policies[i]}")

# 3. Generate: the LLM answers from the found text only.
client = anthropic.Anthropic()   # reads ANTHROPIC_API_KEY from your environment
reply = client.messages.create(
    model="claude-haiku-5-5",
    max_tokens=200,
    messages=[{
        "role": "user",
        "content": "Answer using only this policy text. If it isn't covered, say you don't know.\n\n"
                   f"Policy:\n{context}\n\nQuestion: {question}",
    }],
)
print(reply.content[0].text)

The two things to compare: the WHERE text LIKE line became model.similarity(...), and a new step hands the result to an LLM. Your data didn’t change. Only the way you search it and present it did.

When NOT to use RAG ⚠️

Here’s the honest part. “The database can’t solve it, AI can” is true only for a specific kind of question.

  • Counts, sums and filters belong to SQL. “How many people took sick leave in March?” needs COUNT(*), not a language model guessing from a few paragraphs.
  • Exact lookups belong to SQL. Employee ID, order number, invoice date: an index answers in milliseconds and never gets it “nearly right”.
  • Small documents may not need retrieval. If all your policies fit in one prompt, just send them all to the LLM and skip the search step.
  • Similar isn’t the same as correct. Meaning-based search can return the 2023 policy and the 2025 update side by side. Keep dates or versions in your data and filter on them.
  • The LLM can still invent things. Tell it to answer only from the given text, show the source line to the user, and let it say “I don’t know”.

A good rule: if the question has an exact answer in a column, use SQL. If the answer is buried in sentences and people will phrase it their own way, consider RAG.

Recap 🎯

Your database stores the answer; RAG helps someone find and read it when they don’t know your exact wording. It doesn’t replace the database, it sits on top of it. Next step: run the “after” script, then ask it something your policies don’t cover (like “Is there a pet insurance plan?”) and check that it says it doesn’t know.

What’s a question your users ask that your current search box can’t handle? Tell me in the comments 👇

Sources