Lesson 1 of 4 Retrieval-Augmented Generation in SQL

RAG Use Cases and Architecture

This lesson explains when retrieval-augmented generation is the right pattern and how a RAG pipeline runs in a SQL database.

Learning outcomes

After completing this lesson, you will be able to:

  • Identify use cases for RAG.
  • Distinguish between RAG, plain T-SQL and a model alone.
  • Describe the steps of a RAG pipeline in T-SQL.

What RAG solves

A language model knows only what it saw in training, which excludes an organization's private and recent data, and it may invent plausible but wrong answers. RAG addresses both: for each question, the solution retrieves relevant data, augments the prompt with it and lets the model generate an answer from that grounding, ideally citing the sources. Typical use cases include the following.

  • Support assistants over manuals, troubleshooting articles and policies.
  • Natural-language product discovery over a catalogue, combining semantic matching with filters such as price and stock.
  • Questions over a customer's own orders, contracts or tickets, where retrieval respects Row-Level Security.
  • Summaries of the records relevant to a case, such as all notes about an account in the last quarter.

When RAG is not the answer

RAG is not needed when a deterministic query answers the question exactly, such as totals, counts and lookups by key; T-SQL is cheaper and always correct for those. When the model must learn a new behaviour or format rather than new facts, fine-tuning or better instructions fit better. The following comparison summarizes the choice.

Plain T-SQL
Best forExact aggregates and lookups
FreshnessCurrent
RiskNone beyond query correctness
Choose when 'Total sales last month'
RAG
Best forAnswers grounded in current private text and data
FreshnessCurrent, retrieved per question
RiskPoor retrieval leads to poor answers
Choose when 'Which tent suits winter camping for two?'
Model alone
Best forGeneral knowledge and language tasks
FreshnessFixed at training time
RiskHallucinated facts about private data
Choose when 'Rewrite this paragraph formally'
Sort into groups

T-SQL, RAG or the model alone?

Exam skills 3.3.1

Choose the approach for each question.

Log in to try this activity Interactive activities are free with an account.

A RAG pipeline in the database

SQL Server 2025, Azure SQL Database and SQL database in Fabric can run the whole pipeline in T-SQL, usually in one stored procedure, as the following steps show.

  1. Embed the question

    AI_GENERATE_EMBEDDINGS(@question USE MODEL EmbeddingModel) into a vector variable.

  2. Retrieve

    Run vector or hybrid search, with security and business filters, and keep the top few chunks or rows.

  3. Serialize

    Convert the retrieved rows to compact JSON with FOR JSON or JSON_ARRAYAGG.

  4. Build the prompt

    Create the chat request body with a system message, the question and the JSON data using JSON_OBJECT.

  5. Call the model

    Send it with sp_invoke_external_rest_endpoint and a managed identity credential.

  6. Extract and return

    Read the answer (and structured fields) with JSON_VALUE or OPENJSON and return it with the source IDs.

Keeping retrieval in the database means the data never leaves it except for the selected rows sent to the model, security rules such as RLS apply automatically, and Data API builder or an agent can call the procedure as one operation. Because answer quality depends mainly on retrieval, the search is evaluated and tuned before the prompt.

The following diagram shows the steps of a RAG pipeline inside the database, written in T-SQL.

A RAG pipeline inside the database, usually one stored procedure. The question is embedded with AI_GENERATE_EMBEDDINGS, vector or hybrid search retrieves the top chunks with security filters, the rows are serialized to compact JSON, a chat request is built with JSON_OBJECT, sent with sp_invoke_external_rest_endpoint using a managed identity, and the answer is extracted with JSON_VALUE or OPENJSON and returned with source IDs. Only the selected rows leave the database, and RLS applies to retrieval automatically.
Retrieval, prompt and model call can run in one procedure.
Put in order

RAG in T-SQL

Exam skills 3.3.2 · 3.3.4

Put the steps of a RAG stored procedure in order.

Log in to try this activity Interactive activities are free with an account.
Worked example

Choosing RAG or a query

A sales portal needs two features: "show my total revenue by month this year" and "which of our products would suit a customer planning a winter trek in Norway?". Which features should use RAG?

Only the second. Revenue by month is an exact aggregate that a T-SQL query (or a report) answers correctly every time; sending it through a model adds cost and risk of error. The product question needs semantic retrieval of suitable products and a natural-language explanation grounded in their descriptions, which is what RAG provides.

Check yourself

What most often causes poor RAG answers?

Show answer

Poor retrieval: if the relevant data is not retrieved, the model cannot use it.

Exam Tips

Remember for the exam

  • Answers from current private data, with citations: RAG.
  • Exact totals and lookups: plain T-SQL.
  • Pipeline: embed question, retrieve, serialize to JSON, build prompt, call model, extract answer.
  • RAG quality depends mostly on retrieval quality.