Lesson 2 of 4 Retrieval-Augmented Generation in SQL

Converting Retrieved Data to JSON for Models

This lesson explains how to serialize retrieved rows to compact, labelled JSON and what to include or leave out.

Learning outcomes

After completing this lesson, you will be able to:

  • Explain why JSON suits model input.
  • Describe how FOR JSON and JSON_ARRAYAGG serialize rows.
  • Identify what data to include in and exclude from prompts.

Why JSON

Language models read text, and JSON is a compact, unambiguous text format that preserves structure: which value belongs to which product, which line belongs to which order. Models handle JSON reliably, and T-SQL produces it safely with built-in functions that escape quotes and special characters. Clear property names act as labels, so the model can tell a price from a weight without extra explanation.

Serializing with FOR JSON and JSON_ARRAYAGG

FOR JSON PATH turns the retrieved rows into a JSON array, with aliases as property names and dotted aliases for nesting. JSON_ARRAYAGG with JSON_OBJECT does the same inline, which fits naturally into building the request.

DECLARE @context nvarchar(max) =
(
    SELECT TOP (5) p.ProductID AS id,
           p.Name AS name,
           p.ListPrice AS price_usd,
           p.WeightKg AS weight_kg,
           LEFT(p.Description, 800) AS description
    FROM Catalog.Product AS p
    JOIN @matches AS m ON m.ProductID = p.ProductID      -- from the vector search
    ORDER BY m.distance
    FOR JSON PATH
);
-- [{"id":42,"name":"Arctic Dome 2","price_usd":349.00,"weight_kg":2.4,"description":"..."}, ...]
True or false

Serializing context

Exam skills 3.3.3

Decide whether each statement about serializing retrieved rows is true.

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

What to send

Every token sent costs money and attention, and everything sent leaves the database, so the data is curated before serialization. The guidelines are summarized in the following table.

GuidelineReason
Include an ID per rowThe model can cite sources, and the application can link to them
Use descriptive property names with unitsprice_usd is unambiguous; p is not
Send only needed columnsSmaller prompts are cheaper and keep the model focused
Limit to the top few results, ordered by relevanceMore context is not better once relevant rows are included
Truncate or chunk long textStays within the context window
Exclude personal and confidential columnsData sent to the model leaves the database
Sort into groups

Send it or leave it out?

Exam skills 3.3.3

Decide whether each item belongs in the JSON sent to the model.

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

A prompt that is too large

A RAG procedure serializes the top 50 retrieved support articles with SELECT * ... FOR JSON AUTO. Requests fail with a context length error, and when they succeed answers are slow and sometimes quote internal notes. What should the developer change?

Select only the needed columns (ID, title, relevant chunk text) with clear aliases, exclude the internal notes column, retrieve chunks rather than whole articles, and keep only the top few by relevance before serializing with FOR JSON PATH. This shrinks the prompt below the context window, speeds responses and stops confidential content leaving the database. Switching to a model with a larger context window would still send internal notes.

Check yourself

Why include an ID for each retrieved row in the prompt?

Show answer

So the model can cite its sources and the application can validate and link them.

Exam Tips

Remember for the exam

  • Serialize retrieved rows with FOR JSON PATH or JSON_ARRAYAGG with JSON_OBJECT.
  • Include an ID per row for citations and use descriptive names.
  • Send only needed, non-sensitive columns and only the top results.
  • Retrieve chunks, not whole documents, to fit the context window.