
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 đ
- A database finds what you ask for exactly. It matches words, numbers and IDs. It doesnât know what a sentence means.
- People ask in their own words, which are often different from the words in your documents.
- RAG adds two things: a search that matches by meaning, and an LLM that reads the found text and writes a plain answer.
- RAG still uses a database. It doesnât replace yours; it reads from it in a smarter way.
- 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.
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 đ