Category: Databases

Identify use cases for RAG (DP-800 Exam Prep)

This post is a part of the DP-800: Developing AI-Enabled Database Solutions Exam Prep Hub.
This topic falls under these sections:
Implement AI capabilities in database solutions (25–30%)
   --> Design and implement retrieval-augmented generation (RAG)
      --> Identify use cases for RAG


Note that there are 10 practice questions (with answers) at the end of each section to help you solidify your knowledge of the material. Also, there are 4 practice tests with 30 questions each available from the hub's main page below the exam topics section.

Introduction

Retrieval-Augmented Generation (RAG) is one of the most important architectural patterns in modern AI-enabled database applications. Rather than relying solely on the knowledge contained within a Large Language Model (LLM), RAG retrieves relevant information from trusted data sources at query time and supplies that information to the model before it generates a response.

For the DP-800 exam, you should understand when RAG is appropriate, which business problems it solves, its advantages and limitations, and the types of applications that benefit most from its use.


What Is Retrieval-Augmented Generation (RAG)?

Retrieval-Augmented Generation (RAG) is an AI architecture that combines:

  • Information retrieval
  • Vector search
  • Large Language Models (LLMs)

Instead of asking an LLM to answer a question solely from its training data, a RAG system first retrieves relevant information from a database, document repository, or knowledge base.

The retrieved information is then included in the prompt sent to the LLM.

The workflow looks like this:

User Question
Generate Query Embedding
Vector or Hybrid Search
Retrieve Relevant Documents
Build Prompt with Retrieved Context
Large Language Model
Grounded Response

This process enables the model to answer using current, organization-specific, and trusted information.


Why RAG Is Needed

LLMs have several limitations when used independently.

These include:

  • Knowledge is limited to training data.
  • Information may become outdated.
  • Models cannot automatically access private organizational data.
  • Responses may contain hallucinations (confident but incorrect information).

RAG addresses these limitations by retrieving external information before response generation.

For example:

Without RAG:

“What is our company’s parental leave policy?”

The LLM has no knowledge of an organization’s private HR documents.

With RAG:

The system retrieves the latest HR policy document and provides it to the LLM, enabling it to generate an accurate, grounded response.


When Should You Use RAG?

RAG is most valuable when answers depend on information that is:

  • Frequently updated
  • Organization-specific
  • Too large to include in prompts directly
  • Stored in databases or documents
  • Required to be accurate and traceable

Typical sources include:

  • SQL databases
  • Knowledge bases
  • PDFs
  • SharePoint libraries
  • Wikis
  • Product documentation
  • Policies
  • Support articles
  • Contracts
  • Technical manuals

Common Business Use Cases

1. Enterprise Knowledge Management

One of the most common RAG implementations is an internal knowledge assistant.

Employees can ask questions such as:

“How do I request family medical leave?”

The system retrieves HR documentation and generates a conversational answer.

Benefits include:

  • Faster information access
  • Reduced HR workload
  • Consistent answers
  • Always uses the latest documents

2. Customer Support

Support organizations often maintain thousands of troubleshooting articles.

Example question:

“Why won’t my VPN connect?”

Instead of requiring agents to manually search documentation, RAG retrieves relevant articles and generates a summarized answer.

Benefits:

  • Faster issue resolution
  • Improved customer satisfaction
  • Reduced training requirements
  • Consistent troubleshooting guidance

3. Technical Documentation Assistants

Software vendors publish extensive documentation.

Example:

“How do I configure Transparent Data Encryption?”

RAG retrieves:

  • Product documentation
  • Configuration guides
  • Best practices

The LLM produces a concise explanation grounded in the documentation.


4. SQL Database Assistants

Database developers may ask:

  • Explain this stored procedure.
  • Which table stores customer addresses?
  • Show the indexing strategy.
  • What permissions exist on this database?

A RAG system retrieves schema information, documentation, and metadata before generating responses.


5. Help Desk Automation

IT departments frequently answer repetitive questions.

Examples:

  • Password resets
  • VPN setup
  • Printer installation
  • Software installation
  • MFA enrollment

RAG enables intelligent self-service portals.


6. Legal Research

Law firms manage:

  • Contracts
  • Regulations
  • Case law
  • Internal legal guidance

RAG retrieves relevant documents before generating summaries.

Benefits:

  • Faster legal research
  • Improved consistency
  • Reduced manual searching

7. Healthcare Knowledge Systems

Healthcare organizations maintain:

  • Clinical guidelines
  • Treatment protocols
  • Internal procedures

RAG retrieves the latest guidance to support clinicians while ensuring answers are based on approved information.


8. Financial Services

Financial institutions use RAG for:

  • Compliance documentation
  • Regulatory guidance
  • Investment research
  • Internal policies

Because regulations change frequently, RAG provides more current information than relying solely on a model’s training data.


9. Product Recommendation Systems

Instead of searching manually through product catalogs:

Customer asks:

“I’m looking for a waterproof hiking backpack.”

RAG retrieves product specifications before the LLM generates recommendations.


10. Research Assistants

Researchers query:

  • Scientific papers
  • Internal reports
  • Publications
  • Technical documents

RAG retrieves relevant documents and summarizes findings.


Industry Examples

IndustryExample RAG Use Case
HealthcareClinical guideline assistant
BankingRegulatory compliance assistant
InsurancePolicy document assistant
ManufacturingEquipment maintenance assistant
RetailProduct recommendation assistant
EducationCourse material assistant
GovernmentCitizen information portal
LegalContract and legal research assistant
TechnologyDocumentation chatbot
Human ResourcesEmployee policy assistant

When RAG Is NOT Necessary

RAG is not the best solution for every AI application.

Examples where RAG may not be required include:

  • Creative writing
  • Brainstorming ideas
  • Poetry generation
  • Fiction writing
  • General conversations
  • Language translation
  • Grammar correction

These tasks rely primarily on the language capabilities of the LLM rather than external knowledge.


RAG vs Fine-Tuning

A common exam topic is distinguishing RAG from fine-tuning.

RAGFine-Tuning
Retrieves external informationModifies model weights
Uses current dataLearns from training data
No retraining required for document updatesRequires retraining for new knowledge
Best for dynamic informationBest for changing model behavior
Uses databases and documentsUses training datasets

Example:

Company updates its vacation policy.

With RAG:

Simply update the knowledge base.

With fine-tuning:

The model would need to be retrained to incorporate the new policy.


Benefits of RAG

Current Information

Answers reflect the latest available documents.


Reduced Hallucinations

The LLM is grounded with trusted information before generating responses.


Organization-Specific Knowledge

Private business data remains outside the foundation model and is retrieved only when needed.


No Model Retraining

Updating documents updates the knowledge available to the system.


Better Accuracy

Responses are based on authoritative content rather than the model’s memory.


Explainability

Many RAG systems cite or link to the documents used to generate responses.


Limitations of RAG

Dependent on Retrieval Quality

Poor retrieval leads to poor responses.


Requires Search Infrastructure

Organizations must maintain:

  • Embeddings
  • Vector indexes
  • Search indexes
  • Metadata
  • Documents

Additional Latency

Searching for documents adds time before the LLM generates a response.


Token Limits

Too many retrieved documents may exceed the LLM’s context window.

Systems typically retrieve only the most relevant documents.


Selecting Good RAG Use Cases

Ideal RAG scenarios include:

  • Large document collections
  • Frequently changing information
  • Private organizational knowledge
  • Regulatory documentation
  • Technical documentation
  • Search-heavy workloads
  • Question-answering systems

Less suitable scenarios include:

  • Pure text generation
  • Entertainment applications
  • Creative storytelling
  • Static knowledge with no need for external sources

RAG in SQL-Based AI Solutions

Modern SQL platforms increasingly support capabilities that enable RAG solutions, including:

  • Vector data types
  • Embedding storage
  • Vector indexes
  • Hybrid search
  • Similarity search
  • Integration with Azure AI services
  • Secure access to structured and unstructured enterprise data

This allows developers to build AI applications that combine relational data with semantic search in a single solution.


Best Practices

  • Use RAG for applications requiring current or organization-specific information.
  • Build high-quality vector indexes and embeddings to improve retrieval accuracy.
  • Combine vector search with keyword search using hybrid search when appropriate.
  • Retrieve only the most relevant documents to stay within LLM context limits.
  • Apply security trimming so users retrieve only documents they are authorized to access.
  • Regularly update embeddings and indexes when source content changes.
  • Monitor retrieval quality using metrics such as precision, recall, and user feedback.
  • Include citations or source references whenever possible to increase trust.

DP-800 Exam Tips

Remember these key points for the exam:

  • RAG retrieves external information before the LLM generates a response.
  • RAG is ideal for organization-specific, frequently changing, or private knowledge.
  • RAG reduces hallucinations by grounding responses in retrieved documents.
  • RAG is commonly used with vector search and hybrid search.
  • RAG differs from fine-tuning because it does not modify the model’s weights.
  • Updating a knowledge base is typically sufficient to provide new information to a RAG system.
  • Common RAG use cases include enterprise search, customer support, technical documentation, compliance, and knowledge management.
  • Strong retrieval quality is essential because poor retrieval leads to poor AI responses.

Practice Exam Questions

Question 1

A company wants an AI assistant that answers employee questions using the latest HR policies stored in an internal document repository.

Which AI architecture is the most appropriate?

A. Fine-tune a language model every time a policy changes.

B. Use Retrieval-Augmented Generation (RAG).

C. Train a new embedding model monthly.

D. Use only keyword search without an LLM.

Answer: B

Explanation:
RAG retrieves the latest HR documents at query time and provides them to the LLM, allowing responses to reflect current policies without retraining the model.


Question 2

Which scenario is the best candidate for implementing a RAG solution?

A. Generating original poetry

B. Creating fictional stories

C. Answering questions using frequently updated product documentation

D. Producing creative marketing slogans

Answer: C

Explanation:
RAG excels when responses depend on current, external, or organization-specific information, such as product documentation that changes over time.


Question 3

Why does RAG generally reduce hallucinations compared to using an LLM alone?

A. It increases the model’s parameter count.

B. It permanently stores retrieved documents inside the model.

C. It grounds responses using relevant retrieved information.

D. It eliminates vector search.

Answer: C

Explanation:
By providing the LLM with relevant documents before response generation, RAG enables the model to base its answers on trusted information instead of relying solely on its training data.


Question 4

A legal firm needs an AI assistant that answers questions using thousands of contracts and regulatory documents that change regularly.

Which solution is most appropriate?

A. Static prompting only

B. Fine-tuning only

C. Rule-based automation

D. Retrieval-Augmented Generation (RAG)

Answer: D

Explanation:
RAG is well suited for dynamic document collections because updated documents become available to the AI system without requiring model retraining.


Question 5

Which statement correctly distinguishes RAG from fine-tuning?

A. RAG modifies the model’s internal weights.

B. Fine-tuning retrieves external documents during every query.

C. RAG retrieves external information at query time, while fine-tuning changes the model through additional training.

D. There is no practical difference between the two approaches.

Answer: C

Explanation:
RAG supplements a model with retrieved context, whereas fine-tuning changes the model’s learned behavior through additional training.


Question 6

A company updates its employee handbook every month.

What is typically required for a RAG solution to use the latest information?

A. Retrain the large language model.

B. Replace the vector database.

C. Update the document repository, regenerate embeddings if needed, and refresh the search index.

D. Reinstall the AI application.

Answer: C

Explanation:
RAG systems rely on current indexed content. When documents change, embeddings and indexes should be refreshed so the retrieval system can locate the updated information.


Question 7

Which use case is generally least appropriate for a RAG implementation?

A. Internal IT help desk assistant

B. Regulatory compliance assistant

C. Technical documentation chatbot

D. Creative short story generation

Answer: D

Explanation:
Creative writing tasks primarily depend on the language generation capabilities of the model and typically do not require retrieval from external knowledge sources.


Question 8

A financial institution wants an AI solution that always references the latest compliance documents before answering user questions.

What is the primary advantage of using RAG?

A. It permanently stores compliance documents inside the LLM.

B. It enables responses based on current external documents without retraining the model.

C. It eliminates the need for search indexes.

D. It automatically fine-tunes the LLM after every document update.

Answer: B

Explanation:
RAG retrieves current compliance documentation during each query, ensuring responses reflect the latest available information while avoiding repeated model retraining.


Question 9

Which technology is most commonly paired with RAG to retrieve semantically relevant documents?

A. Primary key indexes

B. Trigger-based replication

C. Vector search

D. Transaction log backups

Answer: C

Explanation:
Vector search retrieves semantically similar documents using embeddings and is a foundational component of most modern RAG implementations.


Question 10

A database developer is evaluating potential AI projects.

Which project would benefit the most from a RAG architecture?

A. A calculator that performs arithmetic operations

B. A chatbot that answers questions using an organization’s internal SQL documentation and knowledge base

C. A utility that formats SQL code

D. A script that generates random passwords

Answer: B

Explanation:
A chatbot that relies on organization-specific documentation is an ideal RAG use case because it requires access to current, trusted knowledge that is not contained within the LLM’s training data.


Go to the DP-800 Exam Prep Hub main page

Create a prompt by using the sp_invoke_external_rest_endpoint stored procedure (DP-800 Exam Prep)

This post is a part of the DP-800: Developing AI-Enabled Database Solutions Exam Prep Hub.
This topic falls under these sections:
Implement AI capabilities in database solutions (25–30%)
   --> Design and implement retrieval-augmented generation (RAG)
      --> Identify use cases for RAG


Note that there are 10 practice questions (with answers) at the end of each section to help you solidify your knowledge of the material. Also, there are 4 practice tests with 30 questions each available from the hub's main page below the exam topics section.

Introduction

As SQL databases increasingly integrate with AI services, developers can call external REST APIs directly from Transact-SQL (T-SQL). One important capability is the sp_invoke_external_rest_endpoint system stored procedure, which enables SQL code to securely invoke REST endpoints, including AI services such as Azure AI Foundry models, Azure OpenAI Service, and other HTTP-based APIs.

For the DP-800 exam, you should understand how to use this stored procedure to build prompts, send requests to AI models, process responses, and incorporate Retrieval-Augmented Generation (RAG) workflows into SQL applications.


What Is sp_invoke_external_rest_endpoint?

sp_invoke_external_rest_endpoint is a system stored procedure that enables T-SQL code to invoke external REST APIs directly from supported SQL platforms, such as Azure SQL Database and SQL Server 2025 (where supported and configured).

Instead of requiring an application layer to call an external AI service, the database itself can send an HTTPS request and receive the response.

Typical workflow:

T-SQL
sp_invoke_external_rest_endpoint
REST API
AI Model
JSON Response
SQL Processing

This capability allows SQL applications to integrate directly with AI-powered services while keeping business logic close to the data.


Why Use sp_invoke_external_rest_endpoint?

Many AI services expose REST APIs.

Examples include:

  • Azure OpenAI
  • Azure AI Foundry models
  • Azure AI Language
  • Azure AI Translator
  • Azure AI Vision
  • Custom REST APIs
  • Internal enterprise AI services

Using sp_invoke_external_rest_endpoint enables SQL developers to:

  • Generate AI responses
  • Summarize database content
  • Perform sentiment analysis
  • Translate text
  • Classify documents
  • Invoke Retrieval-Augmented Generation (RAG) workflows
  • Call custom enterprise AI services

Role in Retrieval-Augmented Generation (RAG)

In a RAG solution, the database typically performs several tasks:

  1. Retrieve relevant documents.
  2. Build the prompt.
  3. Call the LLM.
  4. Return the grounded response.

Example workflow:

User Question
Vector Search
Retrieve Context
Build Prompt
sp_invoke_external_rest_endpoint
Large Language Model
Grounded Answer

The stored procedure serves as the bridge between SQL and the external AI model.


Components of an AI Request

A typical AI request contains several elements.

Endpoint URL

The REST endpoint specifies where the request is sent.

Examples include:

  • Azure OpenAI endpoint
  • Azure AI Foundry endpoint
  • Internal REST API

HTTP Method

Most AI inference requests use:

POST

because prompt data is sent in the request body.


HTTP Headers

Headers commonly include:

  • Authorization
  • Content-Type
  • API version (when required)
  • Subscription key (for applicable services)

Example:

Content-Type: application/json
Authorization: Bearer <token>

Authentication methods vary by service and may use Microsoft Entra ID (formerly Azure Active Directory), managed identities, or API keys.


JSON Request Body

The request body contains:

  • Prompt
  • System instructions
  • User input
  • Generation parameters

Example:

{
"messages": [
{
"role": "system",
"content": "You are a SQL assistant."
},
{
"role": "user",
"content": "Explain clustered indexes."
}
]
}

The exact JSON schema depends on the AI service being called.


Creating Effective Prompts

Prompt engineering significantly affects AI output quality.

A good prompt should include:

  • Clear instructions
  • Business context
  • Retrieved documents (for RAG)
  • User question
  • Expected output format

Example Prompt Structure

System:
You are an expert SQL assistant.
Context:
<Document retrieved from vector search>
Question:
How do clustered indexes improve performance?
Instructions:
Answer only using the supplied context.

This structure helps reduce hallucinations and produces grounded responses.


Building Prompts in SQL

Developers often assemble prompts dynamically using T-SQL variables.

Conceptually:

DECLARE @Context NVARCHAR(MAX);
DECLARE @Question NVARCHAR(MAX);
SET @Context =
'Clustered indexes store table rows in key order...';
SET @Question =
'Explain clustered indexes.';

The prompt can then be incorporated into the JSON request body before invoking the external endpoint.

Note: The exact JSON construction depends on the target AI service’s REST API.


Example Workflow

A simplified workflow is:

Retrieve Documents
Build Prompt
Create JSON Payload
Call REST Endpoint
Receive JSON Response
Extract Generated Answer

Conceptual Example

The following simplified example illustrates the overall flow. It is not intended to represent every required parameter or authentication option.

EXEC sp_invoke_external_rest_endpoint
@method = 'POST',
@url = 'https://<ai-endpoint>',
@headers = '{"Content-Type":"application/json"}',
@payload = '{"messages":[...]}';

The supported parameters, authentication methods, and payload format depend on the SQL platform and the REST API being invoked.


Using Retrieved Context in RAG

Suppose vector search returns:

Document:

Clustered indexes physically organize rows according to the index key.

User asks:

Why are clustered indexes faster?

Prompt:

Use only the following information:
Clustered indexes physically organize rows according to the index key.
Question:
Why are clustered indexes faster?

This grounded prompt improves response accuracy.


Processing the Response

Most AI services return JSON.

Example (simplified):

{
"choices": [
{
"message": {
"content": "Clustered indexes improve performance because..."
}
}
]
}

SQL applications can use JSON functions such as:

  • OPENJSON
  • JSON_VALUE
  • JSON_QUERY

to extract values from the response.

Example:

SELECT JSON_VALUE(@Response,
'$.choices[0].message.content');

Authentication Considerations

REST endpoints must be secured.

Depending on the service, authentication may use:

  • Microsoft Entra ID
  • Managed Identity
  • API Keys
  • OAuth access tokens

Developers should avoid embedding secrets directly in T-SQL code.

Instead, use secure credential management mechanisms supported by the platform.


Error Handling

Common failures include:

Authentication Errors

Examples:

  • Invalid token
  • Expired credentials
  • Missing permissions

Network Errors

Examples:

  • Endpoint unavailable
  • Timeout
  • DNS failures

Invalid Request

Examples:

  • Incorrect JSON
  • Unsupported parameter
  • Missing required fields

Rate Limiting

Many AI services enforce request limits.

Applications should be designed to handle HTTP responses such as:

  • 429 Too Many Requests

using retry logic with exponential backoff where appropriate.


Performance Considerations

Calling external AI services introduces additional latency.

Factors include:

  • Network communication
  • AI inference time
  • Prompt size
  • Response size
  • Concurrent requests

Large prompts increase:

  • Token usage
  • Response time
  • Cost

Developers should include only the most relevant retrieved context.


Security Best Practices

When invoking external AI services:

  • Use HTTPS endpoints.
  • Authenticate securely using supported identity mechanisms.
  • Protect API credentials.
  • Validate user input before constructing prompts.
  • Avoid exposing confidential information unnecessarily.
  • Apply least-privilege access.
  • Monitor outbound API usage.
  • Log failures for troubleshooting while avoiding logging sensitive prompt content.

Best Practices for Prompt Design

  • Provide clear system instructions.
  • Include only relevant retrieved context.
  • Tell the model to answer using the supplied context.
  • Specify the desired output format.
  • Keep prompts concise to reduce latency and token consumption.
  • Remove duplicate or irrelevant information.
  • Test prompts using realistic business questions.
  • Evaluate responses for accuracy and consistency.

Common RAG Prompt Pattern

A common prompt template includes:

System
Instructions
Retrieved Context
User Question
Expected Response Format

This structure helps produce consistent, grounded responses.


DP-800 Exam Tips

Remember these key points for the exam:

  • sp_invoke_external_rest_endpoint enables T-SQL code to call external REST APIs directly.
  • In RAG solutions, the stored procedure is commonly used after retrieving relevant documents and constructing a grounded prompt.
  • AI requests typically use the HTTP POST method with a JSON payload.
  • Prompt quality directly influences response quality.
  • Include retrieved context to reduce hallucinations.
  • Responses from AI services are typically returned as JSON and can be parsed using SQL JSON functions.
  • Secure authentication is essential; avoid hard-coding credentials.
  • Minimize prompt size to improve performance and reduce token costs.

Practice Exam Questions

Question 1

A developer wants to call an Azure AI model directly from T-SQL without writing application code.

Which SQL capability enables this functionality?

A. sp_execute_external_script

B. OPENROWSET

C. sp_invoke_external_rest_endpoint

D. BULK INSERT

Answer: C

Explanation:
sp_invoke_external_rest_endpoint enables supported SQL platforms to invoke external REST APIs directly from T-SQL, making it suitable for integrating AI services.


Question 2

In a Retrieval-Augmented Generation (RAG) solution, when is sp_invoke_external_rest_endpoint typically called?

A. Before documents are retrieved.

B. After relevant context has been retrieved and incorporated into the prompt.

C. Before embeddings are generated.

D. Before the vector index is created.

Answer: B

Explanation:
In a typical RAG workflow, relevant documents are first retrieved using vector or hybrid search. The retrieved context is then included in the prompt before calling the LLM through the REST endpoint.


Question 3

Which HTTP method is most commonly used when invoking an AI chat completion REST endpoint?

A. GET

B. DELETE

C. PUT

D. POST

Answer: D

Explanation:
AI inference requests generally send prompts and parameters within the request body, making POST the standard HTTP method.


Question 4

What is the primary benefit of including retrieved documents in the prompt sent to an AI model?

A. It permanently trains the language model.

B. It reduces network latency.

C. It grounds the response using relevant information.

D. It compresses the prompt.

Answer: C

Explanation:
Including retrieved context allows the model to generate responses based on trusted information, improving accuracy and reducing hallucinations.


Question 5

Which SQL functionality is commonly used to extract generated text from a JSON response returned by an AI service?

A. JSON_VALUE

B. MERGE

C. PIVOT

D. ROW_NUMBER

Answer: A

Explanation:
Functions such as JSON_VALUE, JSON_QUERY, and OPENJSON enable SQL developers to parse JSON responses returned by REST APIs.


Question 6

A developer is designing prompts for an AI-powered SQL assistant.

Which prompt design practice generally produces the most reliable responses?

A. Include unrelated historical data to provide additional context.

B. Keep prompts vague so the model has more flexibility.

C. Provide clear instructions and include only relevant retrieved context.

D. Omit the user’s question whenever possible.

Answer: C

Explanation:
Clear instructions and focused, relevant context help the model generate accurate, grounded, and consistent responses.


Question 7

Which authentication approach is recommended when calling secured AI REST endpoints from SQL?

A. Store API keys directly in every stored procedure.

B. Use supported secure authentication mechanisms such as Microsoft Entra ID or managed identities where available.

C. Disable authentication during development and production.

D. Send credentials as query-string parameters.

Answer: B

Explanation:
Secure authentication methods reduce the risk of credential exposure and align with security best practices for accessing external services.


Question 8

What is a common consequence of including excessive retrieved content in a prompt?

A. Lower token usage.

B. Faster inference times.

C. Reduced storage requirements.

D. Increased latency and higher token consumption.

Answer: D

Explanation:
Longer prompts require more tokens to process, increasing inference time, cost, and the likelihood of exceeding the model’s context window.


Question 9

A database application receives an HTTP 429 response from an AI REST endpoint.

What does this response typically indicate?

A. The JSON response is malformed.

B. Authentication failed.

C. The request exceeded the service’s rate limit.

D. The endpoint only accepts GET requests.

Answer: C

Explanation:
HTTP 429 (“Too Many Requests”) indicates that the client has exceeded the allowed request rate. Applications should implement appropriate retry strategies.


Question 10

Which sequence best represents a typical RAG workflow implemented from SQL?

A. Generate response → Retrieve documents → Build prompt → Parse JSON

B. Retrieve documents → Build prompt → Invoke sp_invoke_external_rest_endpoint → Parse the JSON response

C. Create vector index → Generate embeddings → Train the LLM

D. Build prompt → Delete vector index → Generate embeddings

Answer: B

Explanation:
A typical SQL-based RAG workflow retrieves relevant documents, constructs a grounded prompt, invokes the external AI service using sp_invoke_external_rest_endpoint, and then parses the returned JSON response for use by the application.


Go to the DP-800 Exam Prep Hub main page

Convert structured data to JSON for language model processing (DP-800 Exam Prep)

This post is a part of the DP-800: Developing AI-Enabled Database Solutions Exam Prep Hub.
This topic falls under these sections:
Implement AI capabilities in database solutions (25–30%)
   --> Design and implement retrieval-augmented generation (RAG)
      --> Convert structured data to JSON for language model processing


Note that there are 10 practice questions (with answers) at the end of each section to help you solidify your knowledge of the material. Also, there are 4 practice tests with 30 questions each available from the hub's main page below the exam topics section.

Introduction

Modern AI-enabled database applications frequently need to send structured data stored in relational tables to Large Language Models (LLMs). Because LLMs interact with text or structured payloads such as JSON rather than relational tables, developers must transform SQL query results into JSON before sending them to AI services.

For the DP-800 exam, you should understand how to convert relational data into JSON using SQL, why JSON is the preferred interchange format for AI services, how JSON is used in Retrieval-Augmented Generation (RAG) workflows, and the best practices for preparing structured data for language model processing.


Why Convert Structured Data to JSON?

Relational databases organize information into:

  • Tables
  • Rows
  • Columns
  • Relationships

Large Language Models, however, consume:

  • Natural language
  • JSON documents
  • API payloads
  • Structured text

JSON (JavaScript Object Notation) provides a lightweight, hierarchical format that is easy for applications, APIs, and AI models to process.

Instead of sending an entire table, developers typically send only the relevant records formatted as JSON.


Role of JSON in AI Applications

JSON serves as the common data exchange format between SQL databases and AI services.

Typical workflow:

SQL Database
Query Structured Data
Convert to JSON
Build AI Prompt
REST API Request
Large Language Model
AI Response

This process allows structured business data to become part of an AI prompt or API request.


What Is JSON?

JSON is a text-based format consisting of key-value pairs and arrays.

Example:

{
"CustomerID": 1001,
"CustomerName": "Contoso Ltd.",
"Country": "USA",
"CreditLimit": 50000
}

Nested objects are also supported.

Example:

{
"OrderID": 1055,
"Customer": {
"Name": "Contoso Ltd.",
"Country": "USA"
}
}

Hierarchical structures like these are easier for language models to interpret than tabular data.


Why AI Models Prefer JSON

JSON provides several advantages:

  • Human-readable
  • Machine-readable
  • Structured
  • Flexible
  • Widely supported
  • Easily serialized
  • Easily parsed

Most AI REST APIs accept JSON request bodies and return JSON responses.


Converting SQL Query Results to JSON

Modern SQL platforms support generating JSON directly from query results.

For example, SQL Server and Azure SQL Database provide the FOR JSON clause.

Example:

SELECT CustomerID,
CustomerName,
Country
FROM Customers
FOR JSON AUTO;

Sample output:

[
{
"CustomerID":1001,
"CustomerName":"Contoso Ltd.",
"Country":"USA"
},
{
"CustomerID":1002,
"CustomerName":"Fabrikam",
"Country":"Canada"
}
]

This JSON can be incorporated into prompts or REST API requests.


FOR JSON AUTO

FOR JSON AUTO automatically generates JSON based on the structure of the SELECT statement.

Advantages:

  • Minimal configuration
  • Quick generation
  • Good for simple queries

Example:

SELECT ProductID,
ProductName,
Price
FROM Products
FOR JSON AUTO;

FOR JSON PATH

FOR JSON PATH provides greater control over the resulting JSON structure.

Example:

SELECT
CustomerID AS 'Customer.ID',
CustomerName AS 'Customer.Name'
FOR JSON PATH;

Output:

[
{
"Customer": {
"ID":1001,
"Name":"Contoso Ltd."
}
}
]

FOR JSON PATH is preferred when a specific JSON schema is required by an application or AI service.


Creating Nested JSON

Nested JSON is useful for representing parent-child relationships.

Example:

Customer

Orders

Order Items

Instead of returning multiple unrelated tables, developers can build a hierarchical JSON document that mirrors the business object.

This format is often easier for an LLM to understand.


Using JSON in Prompts

Rather than embedding raw SQL results, developers can include JSON as structured context.

Example prompt:

Use the following customer information:
{
"CustomerID":1001,
"Name":"Contoso Ltd.",
"Country":"USA",
"CreditLimit":50000
}
Summarize the customer's profile.

The structured format enables the model to identify fields and values more reliably.


JSON in Retrieval-Augmented Generation (RAG)

In RAG applications, retrieved information often comes from:

  • SQL queries
  • Vector search
  • Hybrid search
  • APIs

Structured query results can be converted to JSON before being added to the prompt.

Workflow:

SQL Query
FOR JSON
Prompt Construction
LLM
Grounded Response

Combining Structured and Unstructured Data

Many AI applications combine relational data with documents.

Example:

Structured data:

{
"OrderID":1055,
"Status":"Shipped"
}

Retrieved documentation:

Orders typically arrive within three business days after shipment.

Prompt:

Order Information:
{
"OrderID":1055,
"Status":"Shipped"
}
Documentation:
Orders typically arrive within three business days.
Answer the customer's question.

This approach gives the LLM access to both factual business data and supporting context.


Reducing Token Usage

Large JSON payloads increase:

  • Prompt size
  • Latency
  • API cost
  • Token consumption

Best practice:

Include only relevant fields.

Instead of:

{
"CustomerID":1001,
"Name":"Contoso",
"Country":"USA",
"Phone":"...",
"Fax":"...",
"CreatedDate":"...",
"LastLogin":"...",
...
}

Use:

{
"CustomerID":1001,
"Country":"USA",
"CreditLimit":50000
}

Only include information required to answer the user’s question.


Security Considerations

Before converting SQL data to JSON:

  • Remove sensitive columns.
  • Exclude personally identifiable information (PII) unless required and authorized.
  • Apply row-level security (RLS).
  • Enforce column-level permissions.
  • Mask confidential values when appropriate.
  • Validate user authorization before retrieving data.

AI models should receive only the data necessary to perform the requested task.


Data Quality Considerations

Language model responses are only as good as the input data.

Ensure that:

  • Missing values are handled appropriately.
  • Duplicate rows are removed.
  • Invalid records are excluded.
  • Data types are consistent.
  • Field names are meaningful.
  • JSON is well-formed and valid.

Poor-quality JSON often leads to inaccurate or confusing AI responses.


Processing AI Responses

Most AI services also return JSON.

Example:

{
"summary":
"Contoso Ltd. is a U.S. customer with a credit limit of $50,000."
}

SQL JSON functions such as:

  • JSON_VALUE
  • JSON_QUERY
  • OPENJSON

can extract values from the response for further processing or storage.


Common Mistakes

Sending Entire Tables

Avoid sending unnecessary rows.

Instead:

Retrieve only relevant records.


Including Too Many Columns

Large prompts increase token usage and cost.


Using Poor Field Names

Prefer:

CustomerName

instead of:

C_Name

Clear field names help improve model understanding.


Ignoring Security

Never expose confidential information unnecessarily.


Creating Invalid JSON

Malformed JSON causes REST API failures and prevents AI services from processing requests.


Best Practices

  • Use FOR JSON AUTO for simple JSON generation.
  • Use FOR JSON PATH when custom JSON structures are required.
  • Return only relevant rows and columns.
  • Keep JSON concise to reduce token consumption.
  • Use meaningful field names.
  • Remove confidential or unnecessary information.
  • Validate JSON before sending it to AI services.
  • Combine structured JSON with retrieved documents for RAG scenarios.
  • Parse AI responses using SQL JSON functions.
  • Test prompts using realistic business data.

DP-800 Exam Tips

Remember these key points for the exam:

  • JSON is the standard format for exchanging structured data with AI services.
  • SQL Server and Azure SQL Database support JSON generation using FOR JSON.
  • FOR JSON AUTO automatically formats query results.
  • FOR JSON PATH provides greater control over JSON structure.
  • RAG solutions often include JSON generated from SQL queries as contextual information.
  • Smaller, focused JSON payloads reduce token usage and improve performance.
  • Protect sensitive information before converting data to JSON.
  • SQL JSON functions can parse AI responses returned as JSON.

Practice Exam Questions

Question 1

A database developer needs to send customer records from SQL Server to a Large Language Model through a REST API.

Which format is most appropriate?

A. XML

B. CSV

C. JSON

D. Binary data

Answer: C

Explanation:
JSON is the standard format accepted by most AI REST APIs because it is lightweight, structured, and easy for both applications and language models to process.


Question 2

Which SQL clause automatically converts query results into JSON using the default structure of the SELECT statement?

A. FOR JSON AUTO

B. FOR XML

C. OPENJSON

D. JSON_VALUE

Answer: A

Explanation:
FOR JSON AUTO automatically generates JSON based on the query structure with minimal configuration.


Question 3

A developer needs complete control over the hierarchy and property names in the generated JSON document.

Which SQL feature should be used?

A. FOR XML

B. FOR JSON PATH

C. JSON_QUERY

D. OPENJSON

Answer: B

Explanation:
FOR JSON PATH allows developers to customize the JSON structure, including nested objects and property names.


Question 4

Why is JSON commonly used when interacting with Large Language Models?

A. It permanently stores embeddings.

B. It replaces vector indexes.

C. It provides a structured, machine-readable format that AI services commonly accept.

D. It automatically encrypts database records.

Answer: C

Explanation:
JSON is widely supported by REST APIs and AI services, making it the preferred format for exchanging structured data.


Question 5

In a Retrieval-Augmented Generation (RAG) solution, why might structured SQL query results be converted to JSON?

A. To include structured business data as context in the prompt sent to the language model.

B. To train the language model.

C. To replace vector embeddings.

D. To eliminate REST APIs.

Answer: A

Explanation:
Structured SQL data converted to JSON can be included in the prompt, allowing the LLM to generate grounded responses using current business information.


Question 6

A developer includes every column from a customer table in the JSON payload, even though only two fields are required.

What is the most likely consequence?

A. Improved retrieval accuracy.

B. Lower API costs.

C. Increased prompt size, token consumption, and latency.

D. Automatic JSON compression.

Answer: C

Explanation:
Sending unnecessary data increases the size of the prompt, which leads to higher token usage, longer response times, and increased cost.


Question 7

Which SQL functions are commonly used to extract values from a JSON response returned by an AI service?

A. ROW_NUMBER and MERGE

B. JSON_VALUE, JSON_QUERY, and OPENJSON

C. PIVOT and UNPIVOT

D. STRING_AGG and GROUP BY

Answer: B

Explanation:
SQL Server provides JSON functions such as JSON_VALUE, JSON_QUERY, and OPENJSON for parsing JSON documents and extracting data.


Question 8

Which practice best improves both security and efficiency when preparing JSON for an AI service?

A. Include every available database column.

B. Return the entire table regardless of the user’s request.

C. Remove unnecessary and sensitive information before generating JSON.

D. Convert the JSON into XML before sending it.

Answer: C

Explanation:
Limiting the JSON payload to only necessary, authorized data reduces token usage, improves performance, and protects sensitive information.


Question 9

What is the primary advantage of using nested JSON structures?

A. They reduce the need for SQL joins.

B. They represent hierarchical relationships in a format that is easier for applications and language models to interpret.

C. They automatically generate embeddings.

D. They eliminate the need for REST APIs.

Answer: B

Explanation:
Nested JSON naturally represents parent-child relationships, making complex business objects easier for both applications and AI models to process.


Question 10

A database application receives a JSON response from an AI service.

What is the next step if the application needs to store the generated summary in a SQL table?

A. Convert the JSON to XML.

B. Rebuild the vector index.

C. Parse the JSON response using SQL JSON functions and extract the required value.

D. Generate new embeddings for the response.

Answer: C

Explanation:
After receiving a JSON response, SQL functions such as JSON_VALUE or OPENJSON can extract the generated content for storage or further processing.


Go to the DP-800 Exam Prep Hub main page

Send results to a language model (DP-800 Exam Prep)

This post is a part of the DP-800: Developing AI-Enabled Database Solutions Exam Prep Hub.
This topic falls under these sections:
Implement AI capabilities in database solutions (25–30%)
   --> Design and implement retrieval-augmented generation (RAG)
      --> Send results to a language model


Note that there are 10 practice questions (with answers) at the end of each section to help you solidify your knowledge of the material. Also, there are 4 practice tests with 30 questions each available from the hub's main page below the exam topics section.

Introduction

One of the final steps in a Retrieval-Augmented Generation (RAG) workflow is sending retrieved data to a Large Language Model (LLM). After retrieving relevant information from a SQL database, vector index, or hybrid search system, the application packages the data into a prompt and submits it to an AI model through a REST API. The quality of this process directly affects the accuracy, relevance, security, and efficiency of the generated response.

For the DP-800 exam, you should understand how to prepare retrieved results for language model processing, construct effective prompts, submit requests to AI services, handle responses, and follow best practices for security, performance, and reliability.


Where This Step Fits in a RAG Workflow

A Retrieval-Augmented Generation solution consists of several stages.

User Question
Generate Query Embedding
Vector or Hybrid Search
Retrieve Relevant Documents
Prepare Context
Build Prompt
Send Request to Language Model
Receive AI Response
Return Answer to User

Sending the retrieved results to the language model is the bridge between the retrieval system and the AI model.


Why Send Retrieved Results?

Large Language Models do not automatically have access to:

  • SQL databases
  • Internal documentation
  • Company policies
  • Product catalogs
  • Customer records
  • Knowledge bases

Instead, developers retrieve the necessary information and include it in the prompt sent to the model.

This process grounds the AI response in trusted, current information.


Components of a Request

A typical request sent to a language model includes several elements.

System Instructions

The system message defines the model’s role and behavior.

Example:

You are an expert SQL database assistant.
Answer only using the supplied context.

System instructions establish the rules the model should follow.


Retrieved Context

The retrieved context contains the information found during vector or hybrid search.

Example:

Document:
Clustered indexes physically store rows according to the index key.

Only relevant context should be included.


User Question

The original user request is included.

Example:

Why do clustered indexes improve query performance?

The language model combines the retrieved context with the user question to generate an answer.


Output Instructions

Developers may specify:

  • Response length
  • Formatting
  • Tone
  • JSON output
  • Markdown output
  • Bullet lists

Example:

Provide a concise answer in three bullet points.

Preparing Retrieved Results

Retrieved documents often require preprocessing before being sent to the model.

Common preprocessing tasks include:

  • Removing duplicate documents
  • Eliminating irrelevant information
  • Trimming excessively long content
  • Combining related results
  • Filtering unauthorized information
  • Formatting structured data as JSON when appropriate

Proper preparation improves both response quality and efficiency.


Selecting Relevant Context

Sending too much information can reduce answer quality and increase cost.

Best practice:

Retrieve only the top-ranking documents.

For example:

Instead of sending:

  • 50 documents

Send:

  • Top 3–10 highly relevant documents

The exact number depends on the application’s requirements and the model’s context window.


Structuring the Prompt

A well-organized prompt improves response quality.

A common structure is:

System Instructions
Retrieved Context
User Question
Expected Response Format

Example:

You are a SQL expert.
Context:
Clustered indexes physically organize table rows according to the key.
Question:
Why do clustered indexes improve query performance?
Answer only using the provided context.

Sending Structured Data

Sometimes the retrieved information is relational data rather than documents.

Example SQL output:

CustomerCountryCredit Limit
ContosoUSA50000

Instead of sending the table directly, developers often convert it to JSON.

Example:

{
"Customer":"Contoso",
"Country":"USA",
"CreditLimit":50000
}

JSON provides a structured format that AI services process efficiently.


Calling the Language Model

Most AI services expose REST APIs.

A request typically includes:

  • HTTPS endpoint
  • HTTP POST method
  • Authentication
  • JSON payload

Conceptually:

Prompt
JSON Request
REST API
Language Model
JSON Response

SQL Server and Azure SQL Database can call supported REST endpoints using the sp_invoke_external_rest_endpoint stored procedure where available.


Processing the Response

Most AI services return JSON.

Example:

{
"choices":[
{
"message":{
"content":"Clustered indexes improve performance because..."
}
}
]
}

SQL applications can extract the generated text using JSON functions such as:

  • JSON_VALUE
  • JSON_QUERY
  • OPENJSON

The application can then display, store, or further process the generated response.


Managing Context Windows

Every language model has a maximum context window.

The context window includes:

  • System instructions
  • Retrieved documents
  • User question
  • Previous conversation
  • Generated response

If too much information is included, requests may fail or important information may be truncated.

Developers should:

  • Remove irrelevant content.
  • Retrieve fewer documents.
  • Summarize long documents.
  • Limit prompt size.

Token Usage

Language models process text as tokens.

More retrieved content means:

  • More input tokens
  • Longer inference time
  • Higher API costs
  • Increased latency

Reducing unnecessary context improves both performance and cost efficiency.


Security Considerations

Developers should never send sensitive information unnecessarily.

Examples include:

  • Passwords
  • Authentication secrets
  • Personal identifiers
  • Confidential financial records
  • Protected health information
  • Internal security credentials

Before sending data to an external AI service:

  • Apply row-level security (RLS).
  • Apply column-level security.
  • Remove confidential fields.
  • Mask sensitive values when appropriate.
  • Verify user authorization.

Grounding the Response

One of the primary goals of RAG is grounding.

Grounding means that the model bases its answer on retrieved information rather than relying solely on its internal training.

Example instruction:

Answer only using the supplied documents.
If the answer is unavailable, say you do not know.

This helps reduce hallucinations.


Handling Errors

Common issues include:

Authentication Failures

Examples:

  • Expired tokens
  • Invalid credentials
  • Missing permissions

Network Problems

Examples:

  • Endpoint unavailable
  • Timeouts
  • DNS failures

Rate Limits

AI services may return:

429 Too Many Requests

Applications should implement retry logic using exponential backoff.


Invalid Requests

Examples:

  • Malformed JSON
  • Missing prompt
  • Unsupported parameters

Performance Considerations

Factors affecting performance include:

  • Prompt size
  • Number of retrieved documents
  • Network latency
  • AI model size
  • Token count
  • Response length
  • Concurrent requests

Performance can often be improved by:

  • Sending fewer documents.
  • Using concise prompts.
  • Removing duplicate information.
  • Optimizing retrieval quality.

Common Mistakes

Sending Irrelevant Documents

The language model may generate inaccurate or confusing responses.


Including Entire Database Records

Large prompts increase token usage and cost.


Poor Prompt Design

Ambiguous instructions often produce inconsistent responses.


Ignoring Security

Sensitive information should never be included unless necessary and authorized.


Missing Grounding Instructions

Without guidance, the model may rely on general knowledge instead of retrieved context.


Best Practices

  • Retrieve only the most relevant documents.
  • Use clear system instructions.
  • Include the user’s original question.
  • Organize prompts consistently.
  • Limit prompt size to reduce token usage.
  • Convert structured data to JSON when appropriate.
  • Remove sensitive information before sending requests.
  • Validate JSON payloads.
  • Monitor latency and token consumption.
  • Evaluate AI responses for accuracy and relevance.

Real-World Example

A company stores warranty information in SQL Server.

Workflow:

  1. Customer asks:”Is my laptop still under warranty?”
  2. SQL retrieves:
Product: X500
Purchase Date: January 10, 2025
Warranty: 2 Years
  1. JSON is generated:
{
"Product":"X500",
"PurchaseDate":"2025-01-10",
"Warranty":"2 Years"
}
  1. Prompt sent to the language model:
Use the following warranty information:
{
"Product":"X500",
"PurchaseDate":"2025-01-10",
"Warranty":"2 Years"
}
Answer whether the warranty is still valid.

The language model generates a grounded response using the supplied business data.


DP-800 Exam Tips

Remember these key points for the exam:

  • Sending results to the language model is the final step before AI response generation in a RAG workflow.
  • Retrieved documents should be relevant, concise, and properly formatted.
  • System instructions help guide model behavior.
  • Structured SQL data is often converted to JSON before being included in prompts.
  • Smaller prompts reduce latency and token costs.
  • Grounding instructions help reduce hallucinations.
  • Responses from AI services are typically returned as JSON.
  • Sensitive information should be removed before sending requests to external AI services.

Practice Exam Questions

Question 1

A developer is building a Retrieval-Augmented Generation (RAG) application.

After retrieving relevant documents from a vector search, what is the next logical step?

A. Send the retrieved context to the language model as part of the prompt.

B. Retrain the language model.

C. Rebuild the vector index.

D. Delete duplicate embeddings.

Answer: A

Explanation:
After retrieval, the relevant documents are incorporated into the prompt and sent to the language model so it can generate a grounded response.


Question 2

Why should retrieved documents be included in a prompt sent to a language model?

A. To permanently update the model’s training data.

B. To ground the model’s response using relevant information.

C. To reduce embedding dimensions.

D. To replace vector indexes.

Answer: B

Explanation:
Including retrieved context enables the model to generate responses based on current, authoritative information rather than relying solely on pre-trained knowledge.


Question 3

Which prompt component defines the behavior the language model should follow?

A. Retrieved context

B. User question

C. System instructions

D. JSON response

Answer: C

Explanation:
System instructions establish the role, behavior, and constraints for the language model, such as answering only from the supplied context.


Question 4

A developer sends fifty retrieved documents to a language model, even though only five are relevant.

What is the most likely consequence?

A. Improved grounding accuracy.

B. Reduced API costs.

C. Faster inference.

D. Increased token usage, latency, and potential reduction in response quality.

Answer: D

Explanation:
Including excessive context increases prompt size, consumes more tokens, raises costs, and may dilute the relevance of the information presented to the model.


Question 5

Which format is commonly used to send structured SQL query results to a language model?

A. Binary

B. XML

C. JSON

D. CSV

Answer: C

Explanation:
JSON is the standard format for exchanging structured data with AI services because it is lightweight, hierarchical, and widely supported.


Question 6

What is the primary purpose of grounding instructions such as “Answer only using the supplied context”?

A. Increase the embedding dimension.

B. Reduce hallucinations by limiting the model to retrieved information.

C. Eliminate authentication requirements.

D. Automatically compress prompts.

Answer: B

Explanation:
Grounding instructions encourage the model to base its responses on the retrieved documents instead of relying on unsupported assumptions or prior training.


Question 7

A language model returns its response as JSON.

Which SQL functions can be used to extract the generated answer?

A. MERGE and GROUP BY

B. ROW_NUMBER and RANK

C. STRING_AGG and PIVOT

D. JSON_VALUE, JSON_QUERY, and OPENJSON

Answer: D

Explanation:
SQL Server provides JSON functions that allow applications to parse AI responses and extract specific values from JSON documents.


Question 8

Which security practice is most appropriate before sending retrieved results to an external AI service?

A. Include every available column to maximize context.

B. Remove sensitive or unauthorized information from the retrieved data.

C. Disable row-level security.

D. Send authentication credentials within the prompt.

Answer: B

Explanation:
Only the information necessary for the AI task should be sent. Sensitive data should be removed or masked, and normal security controls should remain in effect.


Question 9

Why is prompt size an important consideration when sending results to a language model?

A. Larger prompts always improve response quality.

B. Prompt size has no effect on AI services.

C. Larger prompts increase token usage, cost, and response latency.

D. Prompt size determines the embedding algorithm.

Answer: C

Explanation:
Every token contributes to processing time and cost. Keeping prompts concise improves performance while reducing API expenses.


Question 10

A company wants an AI assistant to answer questions using current warranty information stored in SQL Server.

Which approach best supports this requirement?

A. Fine-tune the language model every time warranty records change.

B. Store warranty records directly inside the model.

C. Build a RAG workflow that retrieves the current warranty data, formats it appropriately, and sends it to the language model.

D. Disable retrieval and rely only on the model’s training data.

Answer: C

Explanation:
A RAG solution retrieves current business data at query time, formats it (often as JSON), and sends it to the language model, allowing responses to remain accurate without requiring model retraining.


Go to the DP-800 Exam Prep Hub main page

Extract language model responses (DP-800 Exam Prep)

This post is a part of the DP-800: Developing AI-Enabled Database Solutions Exam Prep Hub.
This topic falls under these sections:
Implement AI capabilities in database solutions (25–30%)
   --> Design and implement retrieval-augmented generation (RAG)
      --> Extract language model responses


Note that there are 10 practice questions (with answers) at the end of each section to help you solidify your knowledge of the material. Also, there are 4 practice tests with 30 questions each available from the hub's main page below the exam topics section.

Introduction

After a Large Language Model (LLM) generates a response, database applications must extract the returned content so it can be displayed to users, stored in the database, or used by downstream processes. Because most AI services return results in JSON format, developers must understand how to parse JSON, extract relevant values, handle errors, validate responses, and integrate the output into SQL-based applications.

For the DP-800 exam, you should understand the structure of language model responses, how to extract values using SQL JSON functions, how to handle different response formats, and the best practices for securely and efficiently processing AI-generated output.


Where Response Extraction Fits in a RAG Workflow

Extracting the language model response is one of the final stages in a Retrieval-Augmented Generation (RAG) pipeline.

User Question
Retrieve Relevant Documents
Build Prompt
Send Request to AI Model
Receive JSON Response
Extract Generated Content
Display or Store Results

Without response extraction, the application cannot effectively use the AI-generated answer.


Why AI Responses Are Returned as JSON

Most AI services expose REST APIs.

REST APIs typically exchange data using JSON because it is:

  • Lightweight
  • Human-readable
  • Machine-readable
  • Widely supported
  • Easy to parse

Whether using Azure AI Foundry models, Azure OpenAI Service, or other AI providers, JSON is the standard response format.


Typical Language Model Response

Although the exact schema varies by provider and API version, chat completion APIs commonly return a structure similar to the following:

{
"choices": [
{
"message": {
"role": "assistant",
"content": "Clustered indexes improve performance because the table rows are stored in key order."
}
}
]
}

The application typically extracts only the generated text, while ignoring metadata unless it is needed for monitoring or diagnostics.


Common Elements in AI Responses

A language model response may include:

  • Generated text
  • Response identifier
  • Model name
  • Completion reason
  • Token usage statistics
  • Timestamps
  • Metadata

Example (simplified):

{
"id": "chatcmpl-123",
"model": "gpt-4.1",
"choices": [
{
"message": {
"content": "Answer text..."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 125,
"completion_tokens": 38,
"total_tokens": 163
}
}

Developers often extract both the generated answer and token usage for logging or cost monitoring.


Parsing JSON in SQL

SQL Server and Azure SQL Database provide built-in JSON functions.

The most commonly used are:

  • JSON_VALUE
  • JSON_QUERY
  • OPENJSON

These functions enable developers to retrieve values from JSON returned by an AI service.


Using JSON_VALUE

JSON_VALUE extracts a single scalar value.

Example:

SELECT JSON_VALUE(@Response,
'$.choices[0].message.content');

Result:

Clustered indexes improve performance because...

This is the most common method for retrieving the generated response.


Using JSON_QUERY

JSON_QUERY extracts JSON objects or arrays.

Example:

SELECT JSON_QUERY(@Response,
'$.choices');

This returns the complete choices array rather than a single value.

Use JSON_QUERY when you need an entire object or array for further processing.


Using OPENJSON

OPENJSON converts JSON into relational rows and columns.

Example:

SELECT *
FROM OPENJSON(@Response, '$.choices');

This is useful when:

  • Multiple completions are returned
  • Arrays must be processed
  • Nested JSON must be flattened

Extracting Token Usage

Many AI services report token consumption.

Example:

{
"usage": {
"prompt_tokens":125,
"completion_tokens":40,
"total_tokens":165
}
}

Developers can extract these values.

Example:

SELECT JSON_VALUE(@Response,
'$.usage.total_tokens');

Tracking token usage helps monitor:

  • API costs
  • Performance
  • Resource consumption

Processing Multiple Choices

Some APIs may return multiple candidate responses.

Example:

{
"choices":[
{"message":{"content":"Option 1"}},
{"message":{"content":"Option 2"}}
]
}

Developers can use OPENJSON to iterate through the array and select the preferred response.


Storing AI Responses

Generated responses may be:

  • Displayed to users
  • Saved to SQL tables
  • Logged for auditing
  • Indexed for future retrieval
  • Used by downstream workflows

Example table:

RequestIDUserQuestionAIResponseDateGenerated

Proper storage supports auditing, analytics, and troubleshooting.


Validating Responses

Applications should validate AI responses before using them.

Check for:

  • Missing content
  • Empty responses
  • Malformed JSON
  • Unexpected schema
  • API errors

Validation improves application reliability.


Handling API Errors

Not every REST call succeeds.

Possible errors include:

Authentication Failure

Examples:

  • Invalid token
  • Expired credentials

Network Errors

Examples:

  • Timeout
  • DNS failure
  • Connection failure

Invalid Request

Examples:

  • Malformed JSON
  • Missing prompt
  • Unsupported parameters

Rate Limiting

Example:

429 Too Many Requests

Applications should implement retry logic using exponential backoff where appropriate.


Finish Reasons

Many chat completion APIs include a finish reason.

Examples:

  • stop
  • length
  • content_filter

Meaning:

Finish ReasonDescription
stopNormal completion
lengthMaximum token limit reached
content_filterResponse filtered by safety system

Applications may use this information to determine whether a response is complete.


Processing Structured Output

Some prompts request JSON output rather than plain text.

Example response:

{
"summary":"Order shipped.",
"priority":"High"
}

SQL JSON functions can extract each property individually.

Example:

SELECT JSON_VALUE(@Response,
'$.summary');

Structured outputs are particularly useful for workflow automation.


Security Considerations

When processing AI responses:

  • Validate all returned data.
  • Do not assume responses are always correct.
  • Avoid executing generated SQL without validation.
  • Protect sensitive information.
  • Log responses securely.
  • Apply least-privilege access controls.

Even trusted AI services should be treated as external systems whose outputs require validation.


Performance Considerations

Large responses require:

  • More network bandwidth
  • More parsing time
  • More storage
  • More tokens

Developers should:

  • Limit response length where appropriate.
  • Extract only required fields.
  • Avoid storing unnecessary metadata.
  • Archive logs according to retention policies.

Common Mistakes

Assuming Every Response Has the Same Schema

Different AI services and API versions may return different JSON structures.


Ignoring Errors

Applications should always check for API failures before attempting to parse the response.


Parsing Entire JSON Documents

Extract only the required values to improve efficiency.


Not Validating Responses

Malformed or incomplete responses should be handled gracefully.


Ignoring Token Usage

Monitoring token consumption helps control costs.


Best Practices

  • Parse responses using SQL JSON functions.
  • Use JSON_VALUE for scalar values.
  • Use JSON_QUERY for objects and arrays.
  • Use OPENJSON for arrays and complex JSON.
  • Validate response schemas before processing.
  • Log errors separately from successful responses.
  • Track token usage for monitoring and optimization.
  • Limit stored data to what is necessary.
  • Handle rate limits and transient failures gracefully.
  • Design applications to tolerate API schema changes when possible.

Real-World Example

A customer asks:

“Summarize this support ticket.”

The application:

  1. Retrieves ticket information from SQL.
  2. Sends it to a language model.
  3. Receives:
{
"choices":[
{
"message":{
"content":"The customer reports intermittent login failures caused by expired authentication tokens."
}
}
]
}

The application extracts:

SELECT JSON_VALUE(@Response,
'$.choices[0].message.content');

The extracted summary is displayed to the support agent and optionally stored for future reference.


DP-800 Exam Tips

Remember these key points for the exam:

  • Most language model APIs return JSON responses.
  • JSON_VALUE extracts individual scalar values.
  • JSON_QUERY retrieves JSON objects or arrays.
  • OPENJSON converts JSON arrays and objects into relational data.
  • Applications should validate AI responses before using them.
  • Token usage information helps monitor API costs.
  • Finish reasons indicate how the model completed generation.
  • Handle API errors, rate limits, and malformed responses gracefully.
  • Store only the data needed for business purposes.
  • AI-generated output should always be treated as data that requires validation before use.

Practice Exam Questions

Question 1

A SQL application receives a JSON response from a language model and needs to extract the generated answer.

Which SQL function is most appropriate for retrieving a single text value?

A. JSON_VALUE

B. JSON_QUERY

C. OPENJSON

D. STRING_SPLIT

Answer: A

Explanation:
JSON_VALUE extracts a single scalar value from a JSON document, making it ideal for retrieving the generated response text.


Question 2

A developer wants to retrieve the entire choices array from a language model response.

Which SQL function should be used?

A. ROW_NUMBER

B. JSON_QUERY

C. MERGE

D. JSON_VALUE

Answer: B

Explanation:
JSON_QUERY returns JSON objects or arrays rather than individual scalar values, making it appropriate for extracting the complete choices array.


Question 3

When is OPENJSON most useful?

A. When extracting a single property value.

B. When converting JSON arrays into relational rows and columns.

C. When generating embeddings.

D. When creating vector indexes.

Answer: B

Explanation:
OPENJSON parses JSON arrays and objects into tabular data that can be queried using SQL.


Question 4

Why should applications validate AI responses before using them?

A. JSON responses are always encrypted.

B. Validation reduces database storage requirements.

C. AI responses may be malformed, incomplete, or contain unexpected structures.

D. Validation automatically reduces token usage.

Answer: C

Explanation:
Applications should verify that responses are valid, complete, and conform to the expected schema before processing them.


Question 5

A developer wants to monitor AI service costs.

Which information should be extracted from the response?

A. The database transaction log.

B. Vector dimensions.

C. Token usage statistics.

D. Query execution plans.

Answer: C

Explanation:
Many AI APIs return token usage information, which is useful for monitoring API consumption and estimating costs.


Question 6

What does a finish reason of stop typically indicate?

A. The request exceeded the maximum token limit.

B. The response was blocked by a content filter.

C. The model completed the response normally.

D. Authentication failed.

Answer: C

Explanation:
A finish reason of stop indicates that the model reached a natural completion point without interruption.


Question 7

A developer receives multiple candidate responses from an AI service.

Which SQL feature is best suited for processing all returned responses?

A. JSON_VALUE

B. OPENJSON

C. GROUP BY

D. FOR JSON AUTO

Answer: B

Explanation:
OPENJSON can iterate through arrays, making it ideal for processing multiple response choices.


Question 8

Which practice best improves the reliability of applications consuming AI responses?

A. Assume every response follows the same JSON schema.

B. Execute AI-generated SQL statements without review.

C. Validate the response structure and handle errors gracefully.

D. Ignore API error messages.

Answer: C

Explanation:
Validating responses and implementing robust error handling help applications remain reliable even when API responses change or errors occur.


Question 9

Why should developers avoid storing unnecessary metadata from AI responses?

A. Metadata prevents JSON parsing.

B. It can increase storage requirements without providing business value.

C. Metadata invalidates embeddings.

D. Metadata reduces retrieval accuracy.

Answer: B

Explanation:
Storing only the required information minimizes storage costs and simplifies downstream processing.


Question 10

A SQL application receives the following JSON:

{
"choices":[
{
"message":{
"content":"The shipment will arrive tomorrow."
}
}
]
}

Which value should typically be presented to the end user?

A. The complete JSON document.

B. The choices array.

C. The generated text contained in message.content.

D. The API response identifier.

Answer: C

Explanation:
The value stored in message.content contains the natural-language response generated by the language model and is typically the information displayed to users.


Go to the DP-800 Exam Prep Hub main page

Exam Prep Hub for DP-800: Developing AI-Enabled Database Solutions

Welcome to the DP-800: Developing AI-Enabled Database Solutions Exam Prep Hub!

Welcome to the one-stop hub with information for preparing for the DP-800: Developing AI-Enabled Database Solutions certification exam. The content for this exam helps prepare you to have “subject matter expertise in designing and developing AI-enabled database solutions across Microsoft SQL platforms, including Microsoft SQL Server, Azure SQL, and SQL databases in Microsoft Fabric”.
Upon successful completion of the exam, you earn the Microsoft Certified: SQL AI Developer Associate certification.

This hub provides information directly here (topic-by-topic as outlined in the official study guide), links to a number of external resources, tips for preparing for the exam, practice tests, and section questions to help you prepare. Bookmark this page and use it as a guide to ensure that you are fully covering all relevant topics for the DP-800 exam and making use of as many of the resources available as possible.


Audience profile (from Microsoft’s site)

As a candidate for this Microsoft Certification, you should have subject matter expertise in designing and developing AI-enabled database solutions across Microsoft SQL platforms, including Microsoft SQL Server, Azure SQL, and SQL databases in Microsoft Fabric.
You should also have experience writing T-SQL code and developing databases in Microsoft SQL platforms. Plus, you need to be familiar with continuous integration and continuous deployment (CI/CD) practices in GitHub, AI-assisted development tools, and AI concepts, such as embeddings, vectors, and models.
Your responsibilities include:
- Designing and developing database solutions that include both structured and semi-structured data.
- Integrating AI features into modern and highly scalable enterprise applications.
- Securing, optimizing, and deploying database solutions.
- Implementing AI capabilities in database solutions.
You work closely with application developers; database administrators (DBAs); architects; AI engineers; development, security, operations (DevSecOps) engineers; security and compliance administrators; and other stakeholders to deliver robust, high-performance database solutions that power modern applications and AI-driven experiences.

Skills at a glance (as specified in the official study guide)

  • Design and develop database solutions (35–40%)
  • Secure, optimize, and deploy database solutions (35–40%)
  • Implement AI capabilities in database solutions (25–30%)


Topic-by-Topic Exam Content

[click a topic link to access the content and practice questions for that topic]

Design and develop database solutions (35–40%)

Design and implement database objects

Implement programmability objects

Write advanced T-SQL code

Design and implement SQL solutions by using AI-assisted tools

Secure, optimize, and deploy database solutions (35–40%)

Implement data security and compliance

Optimize database performance

Implement CI/CD by using SQL Database Projects

Integrate SQL solutions with Azure services

Implement AI capabilities in database solutions (25–30%)

Design and implement models and embeddings

Design and implement intelligent search

Design and implement retrieval-augmented generation (RAG)


DP-800 Practice Exams


Important DP-800 Resources

Link to the free, comprehensive, self-paced course on Microsoft Learn:
Course: Develop AI-enabled database solutions

Course DP-800T00-A: Develop AI-enabled database solutions – Training | Microsoft Learn

This course has 3 learning paths. The 3 learning paths and their modules are listed with links below:

(1) Design and develop database solutions

This learning path has 4 modules:
(i) Design and implement database objects with SQL
(ii) Implement programmability objects with SQL
(iii) Write advanced T-SQL code
(iv) Implement SQL solutions by using AI-assisted tools

(2) Secure, optimize, and deploy database solutions

This learning path has 4 modules:
(i) Implement data security and compliance with SQL
(ii) Optimize database performance
(iii) Implement CI/CD by using SQL Database Projects
(iv) Integrate SQL solutions with Azure services

(3) Implement AI capabilities in database solutions

This learning path has 3 modules:
(i) Design and implement models and embeddings with SQL
(ii) Design and implement intelligent search with SQL
(iii) Design and implement RAG with SQL

Link to the certification page:

Link to the “Microsoft Certified: SQL AI Developer Associate” certification page:
https://learn.microsoft.com/en-us/credentials/certifications/developing-ai-enabled-database-solutions/?practice-assessment-type=certification

Link to the study guide:

Link to the Study Guide for DP-800: Developing AI-Enabled Database Solutions:
https://learn.microsoft.com/en-us/credentials/certifications/resources/study-guides/dp-800

YouTube resources:

Get Certified: SQL AI Developer (DP-800) series by Microsoft Reactor

Courses:

These are two highly rated courses for DP-800 on Udemy:


Good luck to you passing the DP-800 Exam!
However, the more preparation you have, the less luck you will need. 🙂

Visit this post to see the list of all the certification preparation hubs available on The Data Community.

Handle changes by using change event streaming (CES), change data capture (CDC), Change Tracking, Azure Functions with SQL trigger binding, or Azure Logic Apps (DP-800 Exam Prep)

This post is a part of the DP-800: Developing AI-Enabled Database Solutions Exam Prep Hub.
This topic falls under these sections:
Secure, optimize, and deploy database solutions (35–40%)
   --> Integrate SQL solutions with Azure services
      --> Handle changes by using change event streaming (CES), change data capture (CDC), Change Tracking, Azure Functions with SQL trigger binding, or Azure Logic Apps


Note that there are 10 practice questions (with answers) at the end of each section to help you solidify your knowledge of the material. Also, there are 4 practice tests with 30 questions each available from the hub's main page below the exam topics section.

Introduction

Modern applications rarely operate in isolation. A single database update often needs to trigger downstream actions such as updating search indexes, synchronizing data warehouses, refreshing caches, sending notifications, invoking APIs, or triggering AI pipelines.

Microsoft SQL Server and Azure SQL provide several mechanisms to detect and react to data changes. The DP-800 exam expects candidates to understand the capabilities, strengths, limitations, and appropriate use cases for each technology.

The primary technologies include:

  • Change Data Capture (CDC)
  • Change Tracking
  • Change Event Streaming (CES)
  • Azure Functions with SQL Trigger Binding
  • Azure Logic Apps

Understanding when and why to use each technology is more important than memorizing implementation details.


Why Change Detection Matters

Applications often need to know when data changes occur without continuously querying every table.

Examples include:

  • Synchronizing CRM and ERP systems
  • Triggering AI workflows after new customer data arrives
  • Updating recommendation engines
  • Refreshing search indexes
  • Sending order confirmation emails
  • Replicating data into Microsoft Fabric
  • Populating analytical data lakes
  • Updating Power BI semantic models

Without an efficient change detection mechanism, applications would have to repeatedly scan entire tables, resulting in:

  • Poor performance
  • Increased costs
  • Higher latency
  • Unnecessary resource utilization

Overview of Available Technologies

TechnologyDetects InsertsUpdatesDeletesProvides Changed ValuesTypical Use
Change TrackingYesYesYesNoLightweight synchronization
Change Data CaptureYesYesYesYesETL and replication
Change Event StreamingYesYesYesEvent streamEvent-driven architectures
Azure Functions SQL TriggerYesYesYesCurrent rowServerless processing
Azure Logic AppsYesYesYesDepends on connectorWorkflow automation

Change Data Capture (CDC)

What is CDC?

Change Data Capture records every data modification that occurs within selected database tables.

Unlike Change Tracking, CDC stores:

  • The type of operation
  • Before and after values (where applicable)
  • Transaction information
  • Log Sequence Numbers (LSNs)
  • Timestamps

CDC reads changes directly from the SQL Server transaction log instead of requiring application modifications.


How CDC Works

  1. User modifies data.
  2. SQL writes changes to the transaction log.
  3. CDC captures the changes.
  4. Changes are written into CDC system tables.
  5. Applications or ETL tools read the captured changes.
Application
SQL Table
Transaction Log
CDC Capture Process
CDC Change Tables
ETL / Azure Data Factory / Fabric

Information Stored by CDC

For every change, CDC stores:

  • Insert
  • Update
  • Delete
  • Transaction sequence
  • Changed columns
  • Original values
  • New values
  • Commit time
  • Log sequence number

This provides a complete history of modifications.


Advantages of CDC

Minimal application changes

Applications continue performing normal INSERT, UPDATE, and DELETE operations.


Incremental processing

Instead of processing millions of rows:

Yesterday:
10 million rows
Today:
Only 1,250 rows changed
CDC processes only 1,250 rows.

This dramatically improves ETL performance.


Supports Historical Analysis

CDC retains detailed change history.

Example:

Customer Name

Original:

John Smith

Updated:

John A. Smith

CDC preserves both versions.


Common CDC Use Cases

  • Azure Data Factory incremental loads
  • Microsoft Fabric ingestion
  • Data warehouse updates
  • Database replication
  • AI training pipelines
  • Audit solutions
  • Event publishing
  • Synchronizing microservices

Limitations

CDC:

  • Uses additional storage
  • Requires SQL Agent jobs (SQL Server)
  • Introduces some overhead
  • Retention must be managed
  • Generates additional transaction log activity

Change Tracking

What is Change Tracking?

Change Tracking is a lightweight feature that records which rows have changed, but does not store the actual changed values.

Instead, it stores metadata indicating:

  • Row changed
  • Row deleted
  • Version number

Applications retrieve the latest row directly from the table.


How Change Tracking Works

Instead of saving old values:

CustomerID 101 changed.

The application retrieves:

SELECT *
FROM Customers
WHERE CustomerID = 101

Only the current version is available.


Advantages

Very lightweight.

Minimal storage.

Minimal performance impact.

Simple synchronization.

Fast processing.


Limitations

Cannot determine:

Old value

New value

Only knows:

Row changed

No historical audit.

No before-and-after comparison.


Best Use Cases

Mobile synchronization

Offline applications

Client synchronization

Web applications

Caching

Incremental refresh

Applications only needing current data


CDC vs Change Tracking

FeatureCDCChange Tracking
Detect InsertsYesYes
Detect UpdatesYesYes
Detect DeletesYesYes
Stores Old ValuesYesNo
Stores New ValuesYesNo
Historical DataYesNo
Storage UsageHigherLower
ETL FriendlyExcellentLimited
SynchronizationGoodExcellent
AuditingExcellentPoor

Choosing Between CDC and Change Tracking

Choose CDC when:

  • Building ETL pipelines
  • Loading data warehouses
  • Creating audit systems
  • Tracking complete history
  • AI model retraining
  • Replication

Choose Change Tracking when:

  • Synchronizing mobile devices
  • Synchronizing applications
  • Detecting row changes only
  • Performance is critical
  • History is unnecessary

Change Event Streaming (CES)

What is Change Event Streaming?

Change Event Streaming is an event-driven approach that publishes database changes as events immediately after they occur.

Instead of applications polling for changes:

Did anything change?
Did anything change?
Did anything change?

The database immediately emits an event.


Event-Driven Architecture

INSERT Order
Database
Event Published
┌────┼────┐
▼ ▼ ▼
Function
Logic App
Service Bus

One database change can notify many downstream services simultaneously.


Advantages

Near real-time processing

Low latency

Highly scalable

Excellent for cloud-native applications

Supports asynchronous processing

Works well with event hubs and messaging systems


Common Scenarios

Order processing

Inventory updates

Recommendation engines

AI pipelines

Search indexing

Notifications

Microservices

IoT

Streaming analytics


Benefits over Polling

Polling example:

Check database every minute

Potential issues:

  • Delayed processing
  • Unnecessary database queries
  • Higher compute costs

Event streaming:

Change occurs
Immediate notification

Much more efficient.


Azure Functions with SQL Trigger Binding

Overview

Azure Functions provide a serverless compute platform capable of automatically executing code when database changes occur.

SQL Trigger Binding enables Azure Functions to react to SQL data modifications without requiring custom polling logic.

Typical workflow:

Database Change
SQL Trigger
Azure Function
Business Logic

Common Scenarios

Automatically:

  • Send emails
  • Generate invoices
  • Update search indexes
  • Invoke AI models
  • Call REST APIs
  • Update Cosmos DB
  • Write to Azure Storage
  • Publish Service Bus messages

Benefits

Serverless

Automatic scaling

Pay only for executions

Minimal infrastructure management

Easy integration with Azure services

Supports event-driven architectures


Example Scenario

A customer places an order.

INSERT Orders

The SQL trigger starts an Azure Function.

The function:

  • Validates inventory
  • Sends confirmation email
  • Updates recommendation engine
  • Notifies shipping
  • Publishes event

No manual polling required.


Azure Logic Apps

What Are Logic Apps?

Azure Logic Apps are low-code workflow automation services that integrate SQL databases with hundreds of Microsoft and third-party services.

Rather than writing custom code, workflows are built visually.

Example:

SQL Row Updated
Logic App
Teams Notification
Outlook Email
SharePoint Update
CRM Update

Common SQL Integrations

SQL Server

Azure SQL Database

Microsoft Dataverse

Dynamics 365

Salesforce

Microsoft Teams

SharePoint

Azure Storage

Azure Service Bus

Azure Event Grid

Power Automate


Typical Workflow

Customer Created
Logic App
Create CRM Record
Send Welcome Email
Create Help Desk Ticket
Notify Sales Team

Advantages

Low-code

Rapid development

Hundreds of connectors

Visual designer

Built-in retry policies

Error handling

Scheduling

Monitoring

Enterprise integration


Limitations

Logic Apps are ideal for orchestration and workflow automation but are not intended for high-throughput transactional processing where custom code or event streaming solutions may provide better scalability and lower latency.


Choosing the Right Technology

RequirementRecommended Solution
Incremental ETLCDC
Data Warehouse LoadingCDC
Audit HistoryCDC
Mobile SyncChange Tracking
Cache RefreshChange Tracking
Event-Driven ProcessingChange Event Streaming
Serverless Business LogicAzure Functions SQL Trigger
Workflow AutomationAzure Logic Apps
AI Pipeline TriggerAzure Functions or CES
Multi-System IntegrationLogic Apps

Best Practices

Enable Only What You Need

Enable CDC or Change Tracking only on tables that require change detection.


Monitor Storage

CDC tables can grow quickly.

Implement retention policies and cleanup jobs.


Prefer Event-Driven Architectures

Avoid continuous polling whenever possible.

Use:

  • CES
  • Azure Functions
  • Event Grid
  • Service Bus

for scalable cloud-native applications.


Separate Operational and Analytical Workloads

Use CDC to move transactional data into analytical platforms instead of querying production systems directly.


Secure Integration Endpoints

Protect Azure Functions and Logic Apps using:

  • Microsoft Entra ID
  • Managed identities
  • Azure Key Vault
  • Least privilege access
  • Network restrictions where appropriate

Monitor Reliability

Track:

  • Failed executions
  • Retry attempts
  • Dead-letter queues
  • Function failures
  • Logic App run history
  • Event delivery failures

DP-800 Exam Tips

Remember these common exam distinctions:

  • CDC records complete data changes, including inserted, updated, and deleted values, making it ideal for ETL, auditing, and replication.
  • Change Tracking records only that a row changed, making it a lightweight solution for synchronization scenarios.
  • Change Event Streaming supports near real-time, event-driven architectures by publishing change events to downstream consumers.
  • Azure Functions with SQL Trigger Binding are best when database changes should execute custom serverless code automatically.
  • Azure Logic Apps are the preferred choice for orchestrating business workflows and integrating SQL databases with Azure and third-party services through low-code connectors.
  • When selecting a technology, evaluate latency requirements, scalability, historical tracking needs, operational overhead, and integration requirements rather than choosing a single solution for every scenario.

Summary

Modern SQL applications extend well beyond traditional databases, serving as event sources for cloud-native architectures, AI pipelines, analytics platforms, and business workflows. Microsoft provides several complementary technologies to detect and process database changes, each optimized for different scenarios.

For the DP-800 exam, you should understand not only how these technologies work, but also when to choose one over another. CDC excels at incremental ETL and auditing, Change Tracking offers lightweight synchronization, Change Event Streaming enables real-time event-driven systems, Azure Functions execute custom business logic in response to changes, and Azure Logic Apps simplify workflow automation across enterprise services.

A solid understanding of these tools will help you design scalable, maintainable, and performant AI-enabled database solutions in Azure.


Practice Exam Questions


Question 1

A company loads data from an Azure SQL Database into a Microsoft Fabric warehouse every hour. The ETL process should retrieve only rows that have changed since the previous load, including the previous and new values of updated rows.

Which technology should you recommend?

A. Change Tracking

B. Change Data Capture (CDC)

C. Azure Logic Apps

D. Azure Functions with SQL Trigger Binding

Correct Answer: B

Explanation

CDC is specifically designed for incremental data movement scenarios. It captures inserts, updates, and deletes directly from the transaction log and stores detailed information about each change, including before and after values where applicable.

Why the other options are incorrect:

  • A: Change Tracking identifies changed rows but does not store previous values.
  • C: Logic Apps orchestrate workflows but do not capture database changes.
  • D: Azure Functions respond to events but are not intended to maintain historical change data for ETL.

Question 2

A mobile application periodically synchronizes customer records with an Azure SQL Database. The application only needs to know which rows have changed since the last synchronization and does not require historical values.

Which feature is most appropriate?

A. Change Event Streaming

B. Azure Functions SQL Trigger

C. Change Tracking

D. CDC

Correct Answer: C

Explanation

Change Tracking is optimized for synchronization scenarios. It records that rows have changed while minimizing storage and processing overhead.

Why the other options are incorrect:

  • A: CES is designed for event-driven architectures.
  • B: Azure Functions execute custom code rather than maintaining synchronization metadata.
  • D: CDC stores detailed change history, which is unnecessary here.

Question 3

An online retailer wants every new order inserted into the Orders table to immediately trigger inventory updates, shipping notifications, and fraud detection.

Which solution best supports this requirement?

A. Scheduled polling queries

B. Change Tracking

C. Change Event Streaming (CES)

D. Nightly ETL jobs

Correct Answer: C

Explanation

CES enables near real-time event publishing whenever database changes occur. Multiple downstream systems can subscribe to the same event without repeatedly querying the database.

Why the other options are incorrect:

  • A: Polling introduces unnecessary latency and database load.
  • B: Change Tracking is intended for synchronization rather than event processing.
  • D: Nightly ETL introduces unacceptable delays.

Question 4

A database update should automatically execute custom C# code that calls several REST APIs and writes audit information to Azure Storage.

Which Azure service should you recommend?

A. Azure Functions with SQL Trigger Binding

B. CDC

C. Change Tracking

D. SQL Agent Job

Correct Answer: A

Explanation

Azure Functions with SQL Trigger Binding automatically execute custom code when qualifying database changes occur, making them ideal for serverless business logic.

Why the other options are incorrect:

  • B: CDC records changes but does not execute code.
  • C: Change Tracking simply records row modifications.
  • D: SQL Agent jobs rely on scheduled execution rather than event-driven processing.

Question 5

Which statement correctly compares Change Tracking and Change Data Capture?

A. CDC captures complete change history while Change Tracking records only that rows changed.

B. Change Tracking captures previous values while CDC does not.

C. Both features store identical information.

D. CDC only tracks INSERT operations.

Correct Answer: A

Explanation

CDC stores detailed information about every change, including inserts, updates, deletes, timestamps, and transaction metadata. Change Tracking only identifies which rows have changed.

The remaining options are incorrect because they reverse the capabilities or incorrectly describe CDC.


Question 6

A business analyst wants to automate the following workflow without writing custom code:

  • Detect a new customer record.
  • Send an Outlook email.
  • Post a Microsoft Teams notification.
  • Update a SharePoint list.

Which solution is the best choice?

A. CDC

B. Azure Logic Apps

C. Change Tracking

D. SQL CLR

Correct Answer: B

Explanation

Azure Logic Apps provide low-code workflow automation with hundreds of built-in connectors, making them ideal for orchestrating business processes across Microsoft services.

Why the other options are incorrect:

  • A: CDC captures changes but does not automate workflows.
  • C: Change Tracking only records modified rows.
  • D: SQL CLR requires custom coding and is not intended for cloud workflow automation.

Question 7

A development team currently polls the database every minute to determine whether new records have been inserted.

What is the primary disadvantage of this design?

A. It reduces database normalization.

B. It prevents indexing.

C. It increases transaction isolation.

D. It generates unnecessary database workload and introduces latency.

Correct Answer: D

Explanation

Polling repeatedly queries the database even when no changes exist, increasing resource consumption while delaying event processing.

Event-driven solutions such as CES or Azure Functions eliminate this inefficiency.


Question 8

Which technology is most appropriate when an organization must maintain a complete historical record of all row changes for regulatory auditing?

A. Azure Logic Apps

B. Change Tracking

C. Change Data Capture

D. Azure Functions

Correct Answer: C

Explanation

CDC preserves detailed information about inserts, updates, deletes, transaction sequence numbers, and timestamps, making it ideal for compliance and auditing.

The other technologies either automate workflows or identify changes without preserving historical values.


Question 9

Which feature is specifically intended to minimize synchronization overhead by storing only metadata about changed rows?

A. Azure Functions SQL Trigger

B. Change Tracking

C. Change Event Streaming

D. Azure Event Grid

Correct Answer: B

Explanation

Change Tracking records lightweight metadata that indicates which rows have changed, allowing applications to retrieve only the latest row versions.

The other options serve different purposes:

  • Azure Functions execute code.
  • CES publishes events.
  • Event Grid distributes events but does not track database modifications.

Question 10

A solution architect is selecting a technology for an event-driven microservices architecture. Multiple independent services must react immediately whenever product inventory changes.

Which solution best satisfies this requirement?

A. Nightly ETL processing

B. Change Tracking

C. Database polling every five minutes

D. Change Event Streaming (CES)

Correct Answer: D

Explanation

CES is designed for event-driven systems where multiple subscribers consume database change events in near real time. It minimizes latency and reduces unnecessary database queries.

Why the other options are incorrect:

  • A: Nightly processing is far too slow.
  • B: Change Tracking is intended for synchronization rather than event broadcasting.
  • C: Polling introduces unnecessary workload and delays.

Exam Tips

For the DP-800 exam, remember these key distinctions:

  • Change Data Capture (CDC) is best for incremental ETL, auditing, replication, and historical change tracking.
  • Change Tracking is designed for lightweight synchronization when only the fact that a row changed is needed.
  • Change Event Streaming (CES) enables near real-time event-driven architectures by publishing database changes to downstream consumers.
  • Azure Functions with SQL Trigger Binding are ideal for executing custom serverless code in response to database changes.
  • Azure Logic Apps provide low-code workflow automation for integrating Azure SQL with Microsoft and third-party services.
  • On the exam, Microsoft often presents multiple technologies that could work. Choose the one that best aligns with the business requirement, considering factors such as latency, historical tracking, automation, scalability, and operational overhead, rather than selecting the most feature-rich option.

Go to the DP-800 Exam Prep Hub main page

Evaluate external models, including multimodal, multilanguage, sizes, and structured output (DP-800 Exam Prep)

This post is a part of the DP-800: Developing AI-Enabled Database Solutions Exam Prep Hub.
This topic falls under these sections:
Implement AI capabilities in database solutions (25–30%)
   --> Design and implement models and embeddings
      --> Evaluate external models, including multimodal, multilanguage, sizes, and structured output


Note that there are 10 practice questions (with answers) at the end of each section to help you solidify your knowledge of the material. Also, there are 4 practice tests with 30 questions each available from the hub's main page below the exam topics section.

Introduction

One of the most important responsibilities of a SQL AI Developer is selecting the appropriate AI model for a given business problem. Microsoft SQL Server, Azure SQL Database, Azure SQL Managed Instance, and Azure AI services increasingly integrate with external Large Language Models (LLMs) and embedding models to provide intelligent capabilities such as natural language querying, document summarization, semantic search, recommendation engines, and Retrieval-Augmented Generation (RAG).

Not every model is suitable for every workload. Larger models generally provide better reasoning but incur higher costs and latency. Smaller models offer faster responses and lower costs but may lack advanced reasoning capabilities. Some models support images and audio (multimodal), while others specialize in text or code. Additionally, many enterprise applications require structured outputs such as JSON rather than free-form text.

For the DP-800 exam, candidates should understand how to evaluate external models based on business requirements, performance, cost, scalability, and AI capabilities.


What Are External Models?

An external model is an AI model that runs outside the database engine and is accessed through an API or AI service.

Examples include:

  • Azure OpenAI models
  • Azure AI Foundry-hosted models
  • Open-source models hosted on Azure AI Foundry or Kubernetes
  • Other cloud-hosted foundation models exposed through REST APIs

Instead of performing AI inference inside SQL Server, the application or database calls an external service.

Example architecture:

Application
Azure SQL Database
Azure OpenAI Service
AI Model
Generated Response

This approach allows SQL-based applications to leverage continuously improving AI models without modifying the database engine.


Factors When Evaluating External Models

Several characteristics should be considered before selecting a model.

These include:

  • Accuracy
  • Reasoning capability
  • Response quality
  • Cost
  • Latency
  • Throughput
  • Context window size
  • Structured output support
  • Multilingual capability
  • Multimodal capability
  • Security and compliance
  • Availability
  • Scalability

Selecting the right model is often a balance between these factors rather than maximizing any single characteristic.


Evaluating Multimodal Models

What Is a Multimodal Model?

A multimodal model can process multiple types of input rather than only text.

Common input types include:

  • Text
  • Images
  • Documents
  • Charts
  • Audio
  • Video (supported by some models)

Example:

A customer uploads:

  • Invoice PDF
  • Photograph of damaged goods
  • Written description

A multimodal model can analyze all three inputs together.


Business Scenarios

Multimodal models are useful for:

  • Document analysis
  • Invoice processing
  • Insurance claims
  • Medical imaging
  • Manufacturing quality inspections
  • Product recognition
  • OCR-enhanced workflows
  • Diagram interpretation

Example:

Instead of asking:

“Describe this invoice.”

The application uploads the invoice itself.

The model extracts:

  • Vendor
  • Invoice number
  • Total
  • Purchase date
  • Line items

Advantages

Multimodal models:

  • Reduce preprocessing
  • Improve accuracy
  • Handle real-world data
  • Simplify AI workflows
  • Support richer user experiences

Limitations

They typically:

  • Cost more
  • Require more compute resources
  • Have higher latency
  • Process larger payloads
  • May not be necessary for text-only applications

Evaluating Multilingual Models

Many enterprise applications serve users around the world.

A multilingual model understands and generates responses in multiple languages without requiring translation.

Example languages include:

  • English
  • Spanish
  • French
  • German
  • Portuguese
  • Japanese
  • Chinese
  • Korean
  • Arabic

Example

Customer question:

Spanish:

¿Cuál es el estado de mi pedido?

The AI responds correctly in Spanish.


Business Benefits

Multilingual models:

  • Improve customer experience
  • Eliminate translation pipelines
  • Simplify global deployments
  • Maintain conversational context across languages
  • Reduce development complexity

Evaluation Criteria

When comparing multilingual models, evaluate:

  • Number of supported languages
  • Translation quality
  • Cultural understanding
  • Domain-specific terminology
  • Consistency across languages
  • Response quality

Common Use Cases

  • Global customer support
  • International e-commerce
  • Government services
  • Travel applications
  • Healthcare portals
  • Financial institutions

Evaluating Model Size

Model size generally refers to the relative complexity and capability of an AI model. While parameter counts are not always publicly disclosed for commercial models, larger models typically provide stronger reasoning at the cost of increased compute requirements.

Generally:

Small model

  • Faster
  • Lower cost
  • Lower latency

Large model

  • Better reasoning
  • Better code generation
  • Better summarization
  • Higher cost
  • Higher latency

Small Models

Ideal for:

  • Chatbots
  • Classification
  • Data extraction
  • Intent detection
  • Basic summarization

Advantages:

  • Fast responses
  • Low operational cost
  • High throughput
  • Efficient scaling

Medium Models

Good balance between:

  • Performance
  • Cost
  • Accuracy

Typical uses:

  • Customer support
  • SQL generation
  • Business assistants
  • Document summarization

Large Models

Best for:

  • Complex reasoning
  • Long documents
  • Advanced coding
  • RAG
  • Planning
  • Agentic AI

Trade-offs include:

  • Higher inference costs
  • Greater latency
  • Increased resource consumption

Latency vs. Accuracy

Every AI solution involves balancing response speed and output quality.

Example:

Customer chatbot

Acceptable latency:

2–3 seconds

Scientific research assistant

Acceptable latency:

10–20 seconds

because answer quality matters more than speed.


Trade-Off Example

RequirementPreferred Model
Fast API responsesSmaller model
High-quality reasoningLarger model
Thousands of concurrent usersSmaller or medium model
Legal document analysisLarger model
AI coding assistantLarger model
FAQ chatbotSmaller model

Context Window Size

The context window defines how much information the model can process in a single request.

A larger context window allows the model to consider more text simultaneously.

Examples include:

  • Long contracts
  • Large knowledge bases
  • Entire manuals
  • Meeting transcripts
  • Large SQL schemas

Benefits

Larger context windows reduce the need to split documents into smaller chunks and help preserve context across lengthy inputs.


Limitations

Larger contexts generally:

  • Increase processing time
  • Increase inference cost
  • Consume more tokens

Applications should include only relevant information rather than maximizing context size unnecessarily.


Structured Output

Many enterprise applications require machine-readable responses instead of conversational text.

Example:

Instead of:

“The customer’s order total is $425 and ships tomorrow.”

Return:

{
"customer":"John Smith",
"orderTotal":425,
"shipDate":"2026-07-29"
}

Structured output allows applications to parse responses reliably.


Why Structured Output Matters

Applications can:

  • Deserialize JSON
  • Populate SQL tables
  • Call stored procedures
  • Trigger workflows
  • Validate data
  • Build dashboards

without performing fragile text parsing.


Common Structured Formats

  • JSON
  • JSON arrays
  • Objects
  • Lists
  • Tables
  • XML (less common)
  • Markdown tables (for presentation)

JSON remains the most common structured format for modern AI integrations.


Function Calling and Tool Use

Many modern models support function calling (also called tool calling), where the model requests that the application invoke predefined functions or APIs instead of generating all information directly.

Example workflow:

User
LLM
Calls:
GetCustomerOrders()
Application
SQL Database
Results
LLM
Final Answer

This approach improves accuracy by combining model reasoning with authoritative business data.


Cost Considerations

AI model selection has a direct impact on operational cost.

Factors affecting cost include:

  • Model complexity
  • Input tokens
  • Output tokens
  • Images processed
  • Audio processed
  • Request volume
  • Concurrency
  • Context window size

A higher-capability model should only be selected when its additional reasoning or multimodal features provide measurable business value.


Benchmarking Models

Before deploying an external model into production, evaluate it against representative workloads.

Typical metrics include:

  • Response accuracy
  • Hallucination rate
  • Latency
  • Cost per request
  • Throughput
  • Reliability
  • Structured output validity
  • Multilingual quality
  • Safety and policy compliance

Use realistic prompts and datasets that reflect production scenarios.


Security and Responsible AI

When integrating external models with SQL-based applications:

  • Protect sensitive data.
  • Apply the principle of least privilege.
  • Use managed identities where possible.
  • Store secrets securely (for example, in Azure Key Vault).
  • Validate AI-generated outputs before acting on them.
  • Avoid sending unnecessary personally identifiable information (PII) to external services.
  • Monitor prompts and responses for safety, quality, and compliance.

Azure OpenAI Model Selection Guidance

Although Microsoft’s available models evolve over time, the evaluation process remains consistent.

When choosing a model, consider:

  • Does the workload require multimodal input?
  • Is multilingual support necessary?
  • What response latency is acceptable?
  • How much reasoning capability is required?
  • Is structured JSON output needed?
  • Will the model participate in a RAG workflow?
  • What are the expected request volumes?
  • What is the available budget?

The best model is the one that satisfies the business requirements while meeting performance, cost, and governance objectives.


Best Practices

  • Match model capability to business requirements.
  • Avoid selecting the largest model unless its advanced capabilities are needed.
  • Use structured outputs whenever applications consume AI responses programmatically.
  • Benchmark multiple models using representative production scenarios.
  • Minimize token usage to reduce costs and improve response times.
  • Use multimodal models only when image, audio, or document understanding is required.
  • Validate generated content before updating databases or executing business processes.
  • Monitor quality, latency, and cost continuously after deployment.

DP-800 Exam Tips

Remember these key distinctions for the exam:

  • Multimodal models process multiple input types, such as text and images.
  • Multilingual models understand and generate content in multiple languages without requiring separate translation services.
  • Smaller models typically provide lower latency and lower cost, making them suitable for high-volume, straightforward tasks.
  • Larger models generally provide stronger reasoning, summarization, and code generation but require more compute resources and incur higher costs.
  • Structured outputs, particularly JSON, are preferred when AI responses must be consumed by applications, APIs, or SQL processes.
  • Function calling allows models to invoke trusted business logic or database operations instead of relying solely on generated responses.
  • Model selection should always balance accuracy, latency, scalability, cost, security, and maintainability.

Summary

Selecting an external AI model is one of the most important architectural decisions in AI-enabled database solutions. The ideal model depends on the workload, whether that involves multilingual customer support, multimodal document analysis, structured data extraction, or advanced reasoning over enterprise data.

For the DP-800 exam, focus on understanding the trade-offs among model capabilities rather than memorizing specific model names. Be prepared to evaluate models based on multimodal support, multilingual performance, reasoning quality, latency, cost, context window size, and structured output capabilities. Equally important is understanding how these models integrate with Azure SQL and Azure AI services to build scalable, secure, and maintainable AI-enabled database solutions.


Practice Exam Questions


Question 1

You are developing an AI-enabled application that summarizes support tickets stored in Azure SQL Database. The application must support English, Spanish, French, German, and Japanese without deploying separate models for each language.

Which type of model best satisfies this requirement?

A. A monolingual English language model with prompt translation
B. A multilingual language model trained on multiple languages
C. A computer vision model with OCR capabilities
D. A speech recognition model

Correct Answer: B

Explanation:
Multilingual large language models (LLMs) are specifically trained to understand and generate text in many languages, eliminating the need to deploy separate models for each supported language. While prompt translation can work, it introduces additional latency and possible translation inaccuracies. Computer vision and speech models are not designed for multilingual text generation.


Question 2

An organization wants an AI model that can analyze scanned invoices, extract tables, understand handwritten notes, and answer user questions about the document.

Which model capability is required?

A. Structured output only
B. Text embedding generation
C. Multimodal processing
D. Sentiment analysis

Correct Answer: C

Explanation:
Multimodal models process multiple input types—including images, documents, handwritten text, and natural language—allowing them to interpret invoices and answer questions. Embedding models create vector representations but do not analyze images directly.


Question 3

You need an AI model that consistently returns data in valid JSON matching a predefined schema for direct insertion into a SQL table.

Which capability should you prioritize?

A. Long context window
B. Large parameter count
C. Function calling only
D. Structured output support

Correct Answer: D

Explanation:
Structured output capabilities ensure responses conform to predefined schemas such as JSON, reducing parsing errors and simplifying database integration. Function calling invokes external operations but does not guarantee JSON schema compliance.


Question 4

Your application performs simple product categorization and sentiment analysis on thousands of customer reviews every minute. Response time and operational cost are more important than handling complex reasoning tasks.

Which model size is the most appropriate?

A. The largest available reasoning model
B. A medium-sized multimodal model
C. A small language model optimized for classification tasks
D. A vision-language model

Correct Answer: C

Explanation:
Simple classification workloads generally do not require large reasoning models. Smaller models provide lower latency, reduced infrastructure costs, and sufficient accuracy for routine categorization and sentiment analysis.


Question 5

A financial institution evaluates several external AI models before deployment.

Which factor should receive the highest priority when handling confidential customer information?

A. Number of supported programming languages
B. Data privacy and regulatory compliance
C. Maximum context window size
D. Availability of image generation

Correct Answer: B

Explanation:
For regulated industries, protecting sensitive information and complying with regulations are primary evaluation criteria. Features such as image generation or larger context windows are secondary if the model cannot satisfy organizational security and compliance requirements.


Question 6

Your organization must choose between two external language models.

Model A produces slightly more accurate answers but averages 8 seconds per response.

Model B is slightly less accurate but consistently responds in under one second.

Which consideration is being evaluated?

A. Tokenization strategy
B. Embedding dimensions
C. Latency versus accuracy tradeoff
D. Database normalization

Correct Answer: C

Explanation:
Model evaluation frequently involves balancing response quality against latency. Interactive applications often prioritize faster responses, while analytical workloads may tolerate longer processing times for greater accuracy.


Question 7

A development team is comparing two embedding models.

One produces 768-dimensional vectors while another produces 3,072-dimensional vectors.

What is generally true?

A. Higher-dimensional embeddings always guarantee better search results.
B. Larger embeddings often improve semantic representation but require more storage and computation.
C. Embedding dimensions have no effect on vector databases.
D. Smaller embeddings always produce higher recall.

Correct Answer: B

Explanation:
Higher-dimensional vectors can capture richer semantic information but increase storage requirements, indexing costs, and similarity search computation. Larger dimensions do not automatically produce better search quality.


Question 8

A healthcare application requires AI-generated discharge summaries that follow a strict template so they can be automatically imported into Azure SQL Database.

Which model feature is most important?

A. Image generation capabilities
B. Speech synthesis support
C. Larger token limits only
D. Structured output generation

Correct Answer: D

Explanation:
Structured outputs enable AI-generated responses to consistently match required formats, such as JSON or predefined schemas, simplifying automated ingestion into databases and reducing validation errors.


Question 9

Why might an organization intentionally choose a smaller external language model instead of the newest, largest model?

A. Smaller models are always more accurate.
B. Smaller models always support more languages.
C. Smaller models often provide lower cost, reduced latency, and sufficient performance for many workloads.
D. Smaller models eliminate the need for prompt engineering.

Correct Answer: C

Explanation:
Many enterprise workloads involve straightforward tasks where the largest model offers minimal additional benefit. Smaller models frequently provide faster responses, lower inference costs, and simpler deployment while meeting performance requirements.


Question 10

An AI-enabled SQL application must process both text and uploaded product images to answer customer questions.

Which model should be recommended?

A. A multimodal language model
B. A text embedding model only
C. A relational database engine
D. A recommendation engine

Correct Answer: A

Explanation:
Multimodal models can simultaneously process textual and visual information, enabling users to ask questions about images and receive context-aware responses. Text embedding models only generate vector representations and cannot directly analyze images.


Exam Tips

For the DP-800 exam, remember these key evaluation principles when selecting external AI models:

  • Select multilingual models when supporting multiple languages without translation pipelines.
  • Choose multimodal models whenever applications must process images, documents, audio, or mixed media.
  • Prefer structured output capabilities when AI responses must populate SQL tables or APIs reliably.
  • Evaluate model size based on workload complexity, balancing cost, latency, throughput, and reasoning ability.
  • Consider privacy, compliance, and data residency before selecting external AI services.
  • Compare models using multiple metrics, including accuracy, latency, throughput, token limits, context window size, scalability, and operational cost.
  • Remember that larger models are not always the best choice—the optimal model is the one that best satisfies the application’s functional, performance, security, and budget requirements.

Go to the DP-800 Exam Prep Hub main page

Create and manage external models (DP-800 Exam Prep)

This post is a part of the DP-800: Developing AI-Enabled Database Solutions Exam Prep Hub.
This topic falls under these sections:
Implement AI capabilities in database solutions (25–30%)
   --> Design and implement models and embeddings
      --> Create and manage external models


Note that there are 10 practice questions (with answers) at the end of each section to help you solidify your knowledge of the material. Also, there are 4 practice tests with 30 questions each available from the hub's main page below the exam topics section.

Introduction

One of the major additions to Microsoft SQL Server 2025, Azure SQL Database, and Azure SQL Managed Instance is the ability to directly integrate with external Artificial Intelligence (AI) models. Rather than exporting data to a separate application, developers can invoke Large Language Models (LLMs), embedding models, or other AI services directly from SQL code. This significantly simplifies the development of intelligent database applications.

For the DP-800 exam, candidates should understand how external models are configured, managed, secured, monitored, and consumed from SQL databases. They should also understand the architectural considerations involved in connecting SQL Server to external AI services such as Azure OpenAI Service, Azure AI Foundry models, GitHub Models, or other OpenAI-compatible endpoints.


What Are External Models?

An external model is an AI model that is hosted outside the SQL database but can be invoked securely from SQL statements.

Instead of training or hosting the model inside SQL Server, SQL sends requests to the model through a configured endpoint.

Examples include:

  • Azure OpenAI GPT models
  • Azure AI Foundry models
  • OpenAI API models
  • GitHub Models
  • Cohere models
  • Meta Llama models
  • Mistral AI models
  • Other OpenAI-compatible endpoints

The SQL database becomes an intelligent application layer capable of performing AI operations while leaving model hosting and scaling to specialized AI services.


Why Use External Models?

External AI models provide capabilities such as:

  • Natural language generation
  • Text summarization
  • Classification
  • Translation
  • Sentiment analysis
  • Content generation
  • Question answering
  • Embedding generation
  • Semantic search
  • Retrieval-Augmented Generation (RAG)

Without external models, these tasks would require exporting database data into an application layer before AI processing.


Benefits of External Models

Using external models provides several advantages:

Reduced Application Complexity

Applications can invoke AI directly from SQL instead of implementing additional middleware.

Centralized Data Processing

Data remains closer to where it is stored, reducing unnecessary movement.

Simplified Development

Developers write SQL instead of building custom AI integration layers.

Enterprise Security

Authentication occurs through secure credentials and managed identities.

Scalability

The external AI provider handles model hosting, GPU infrastructure, scaling, and updates.


External Model Architecture

A typical architecture consists of:

Application
Azure SQL Database
External Model Definition
Credential
HTTPS Endpoint
Azure OpenAI / AI Foundry / OpenAI

SQL sends HTTPS requests to the configured endpoint and returns the model’s response to the calling application.


Components of an External Model

An external model configuration typically includes:

  • Model name
  • Endpoint URL
  • Authentication method
  • API version
  • Deployment name
  • Credentials
  • Optional timeout settings
  • Model capabilities

Supported AI Services

DP-800 focuses primarily on Microsoft’s AI ecosystem.

Common supported services include:

Azure OpenAI Service

Most common deployment option.

Supports:

  • GPT-4
  • GPT-4.1
  • GPT-4o
  • GPT-4 Turbo
  • Embedding models

Azure AI Foundry

Provides access to multiple foundation models from various providers.

Examples include:

  • Meta Llama
  • Mistral
  • Cohere
  • Phi models
  • DeepSeek (where available)

OpenAI-Compatible APIs

SQL can communicate with services implementing the OpenAI API specification.


Creating an External Model

The general process includes:

Step 1

Deploy a model in Azure AI Foundry or Azure OpenAI.


Step 2

Create authentication credentials.

Examples include:

  • API Keys
  • Microsoft Entra ID authentication
  • Managed Identity

Step 3

Create an external model definition inside SQL.

This associates:

  • endpoint
  • deployment
  • credentials
  • model metadata

Step 4

Test connectivity.

Execute SQL queries that invoke the model.


Step 5

Monitor usage.

Review:

  • failures
  • latency
  • token consumption
  • throttling

Authentication Methods

Security is a major exam topic.

Supported authentication methods include:

API Keys

Simple to configure.

Advantages:

  • Easy setup

Disadvantages:

  • Requires secure storage
  • Must be rotated regularly

Microsoft Entra ID

Recommended for enterprise deployments.

Benefits:

  • Central identity management
  • Conditional Access
  • Role-Based Access Control
  • No hardcoded secrets

Managed Identity

Preferred when SQL services interact with Azure services.

Advantages:

  • No passwords
  • Automatic credential rotation
  • Strong security posture

Managing Credentials

Credentials should never be hardcoded into SQL scripts.

Best practices include:

  • Azure Key Vault
  • Managed Identity
  • Secure credential objects
  • Secret rotation
  • Least privilege

Model Configuration Considerations

When selecting a model, evaluate:

  • Latency
  • Cost
  • Context window
  • Maximum tokens
  • Supported languages
  • Multimodal support
  • Structured outputs
  • Function calling
  • Embedding support
  • Regional availability

Model Version Management

AI models evolve frequently.

Developers should:

  • Test new versions
  • Validate prompt compatibility
  • Measure output quality
  • Compare latency
  • Evaluate token costs
  • Deploy gradually

Avoid automatically replacing production models without validation.


Monitoring External Models

Important operational metrics include:

  • Request count
  • Failed requests
  • Average latency
  • Token usage
  • Cost
  • Timeout frequency
  • Authentication failures
  • Rate limiting
  • Model availability

Monitoring may be performed using Azure Monitor, Azure OpenAI metrics, Application Insights, and Log Analytics.


Error Handling

Applications should anticipate failures such as:

  • Network interruptions
  • Authentication failures
  • Invalid prompts
  • Model timeouts
  • Rate limiting
  • Endpoint unavailability
  • Quota exhaustion

Applications should implement:

  • Retry logic
  • Exponential backoff
  • Logging
  • Graceful degradation
  • User-friendly error messages

Cost Management

External AI services typically charge based on token usage.

Cost optimization strategies include:

  • Select smaller models when appropriate.
  • Minimize unnecessary prompts.
  • Cache reusable responses.
  • Use embeddings instead of repeated generation where applicable.
  • Monitor token consumption.
  • Apply rate limits where appropriate.

Security Best Practices

Microsoft recommends:

  • Use Microsoft Entra ID whenever possible.
  • Store secrets securely.
  • Rotate API keys regularly.
  • Restrict network access.
  • Enable auditing.
  • Monitor authentication failures.
  • Apply least privilege.
  • Encrypt data in transit.
  • Avoid sending sensitive information unnecessarily.

Best Practices for DP-800

Candidates should remember the following:

  • External models are hosted outside SQL.
  • SQL communicates with models over secure HTTPS endpoints.
  • Azure OpenAI and Azure AI Foundry are primary Microsoft AI services.
  • Managed Identity is generally preferred over API keys in Azure.
  • Never hardcode secrets.
  • Monitor token usage and latency.
  • Plan for retries and transient failures.
  • Validate model updates before production deployment.
  • Balance performance, cost, and model capabilities.
  • Use the smallest model that satisfies business requirements.

DP-800 Exam Tips

For the exam, be prepared to:

  • Differentiate between external models and local database objects.
  • Understand authentication methods.
  • Identify secure credential storage mechanisms.
  • Select appropriate model types.
  • Monitor AI usage and performance.
  • Recommend enterprise security practices.
  • Manage model lifecycle and versioning.
  • Understand cost optimization strategies.
  • Configure reliable AI integrations.
  • Recognize scenarios where Azure OpenAI or Azure AI Foundry is the preferred solution.

Key Takeaways

Creating and managing external models enables SQL databases to leverage modern AI capabilities without hosting AI infrastructure locally. By securely connecting SQL Server or Azure SQL to services like Azure OpenAI or Azure AI Foundry, developers can incorporate intelligent features such as summarization, classification, semantic search, and RAG directly into database applications. Success depends on proper authentication, secure credential management, monitoring, version control, cost optimization, and selecting the right model for each workload.


Practice Exam Questions

Question 1

A developer wants to enable an Azure SQL Database application to generate natural language summaries using GPT-4o hosted in Azure OpenAI. What is the primary purpose of creating an external model?

A. To copy the AI model into SQL Server memory

B. To allow SQL to securely invoke an externally hosted AI model

C. To convert SQL queries into Python scripts

D. To replace stored procedures with AI-generated code

Correct Answer: B

Explanation: External models define the connection between SQL and an externally hosted AI service. The model remains hosted in Azure OpenAI or another provider, while SQL securely sends requests to it.


Question 2

Which authentication method is generally recommended for Azure SQL Database accessing Azure OpenAI in an enterprise environment?

A. Username and password authentication

B. Shared administrator account

C. Managed Identity

D. Anonymous authentication

Correct Answer: C

Explanation: Managed Identity eliminates the need to store secrets, supports automatic credential rotation, and integrates with Microsoft Entra ID, making it Microsoft’s recommended authentication approach for Azure resources.


Question 3

An organization wants to minimize operational overhead while securely accessing external AI models. Which authentication mechanism best satisfies this requirement?

A. API keys stored in application code

B. SQL logins

C. Managed Identity

D. Local Windows accounts

Correct Answer: C

Explanation: Managed Identity removes the need to manually manage secrets and provides secure, automatic authentication between Azure services.


Question 4

Which factor should be monitored most closely to help control the operational cost of external language models?

A. Token consumption

B. Number of database indexes

C. Memory allocated to SQL Server

D. CPU utilization on the SQL Server

Correct Answer: A

Explanation: Most external LLM providers charge based on token usage. Monitoring prompt and completion tokens helps organizations estimate and manage AI costs.


Question 5

A developer needs to securely store API credentials used by an external model.

Which solution follows Microsoft security best practices?

A. Store the API key in Azure Key Vault

B. Save the API key in a table within the application database

C. Embed the API key in application source code

D. Place the API key in a configuration file committed to source control

Correct Answer: A

Explanation: Azure Key Vault provides secure storage, access policies, auditing, and secret rotation capabilities, making it the recommended location for sensitive credentials.


Question 6

Why should organizations validate new versions of external AI models before deploying them into production?

A. New versions always increase latency.

B. New versions cannot process SQL data.

C. Model behavior, output quality, and performance characteristics may change.

D. SQL Server requires a database restart after every model update.

Correct Answer: C

Explanation: AI model updates can alter response quality, reasoning, formatting, latency, and cost. Testing ensures compatibility with existing applications and prompts.


Question 7

Which capability is provided by Azure AI Foundry that benefits SQL developers?

A. It hosts only Microsoft-developed language models.

B. It provides access to multiple foundation models from different providers.

C. It automatically creates SQL indexes.

D. It replaces Azure SQL Database.

Correct Answer: B

Explanation: Azure AI Foundry offers access to numerous foundation models from Microsoft and third-party providers, enabling developers to select the most appropriate model for their workloads.


Question 8

An external model begins returning timeout errors during peak business hours.

Which application design strategy should be implemented?

A. Disable authentication.

B. Delete and recreate the database.

C. Increase the number of SQL indexes.

D. Implement retry logic with exponential backoff.

Correct Answer: D

Explanation: Transient failures, including timeouts, are common in distributed systems. Retry logic with exponential backoff improves resilience without overwhelming the external service.


Question 9

Which statement best describes an external AI model?

A. It is stored entirely within the SQL database.

B. It executes as a SQL stored procedure.

C. It is hosted externally and accessed through a secure endpoint.

D. It permanently replaces relational queries.

Correct Answer: C

Explanation: External AI models remain hosted outside the database. SQL communicates with them using secure HTTPS requests through configured endpoints.


Question 10

When selecting between multiple external AI models, which combination of evaluation criteria is most appropriate?

A. Number of SQL tables and indexes

B. Latency, cost, capabilities, context window, security, and accuracy

C. File system capacity only

D. Number of database users

Correct Answer: B

Explanation: Choosing the right external model requires balancing functional capabilities with operational considerations such as latency, cost, accuracy, security, supported features, and context window size.


Go to the DP-800 Exam Prep Hub main page

Choose an embedding maintenance method, including table triggers, Change Tracking, Azure Functions with SQL trigger binding, Azure Logic Apps, CDC, CES, and Microsoft Foundry – Part 1 (DP-800 Exam Prep)

This post is a part of the DP-800: Developing AI-Enabled Database Solutions Exam Prep Hub.
This topic falls under these sections:
Implement AI capabilities in database solutions (25–30%)
   --> Design and implement models and embeddings
      --> Choose an embedding maintenance method, including table triggers, Change Tracking, Azure Functions with SQL trigger binding, Azure Logic Apps, CDC, CES, and Microsoft Foundry


Note that there are 10 practice questions (with answers) at the end of each section to help you solidify your knowledge of the material. Also, there are 4 practice tests with 30 questions each available from the hub's main page below the exam topics section.

Introduction

One of the most important aspects of building AI-enabled database applications is maintaining the accuracy of vector embeddings. Embeddings represent the semantic meaning of data at a specific point in time. Whenever the underlying source data changes, the associated embeddings may become outdated. If stale embeddings remain in a vector index, semantic search, Retrieval-Augmented Generation (RAG), recommendation engines, and AI assistants can produce inaccurate or misleading results.

For the DP-800 exam, candidates should understand the various methods available to detect changes to relational data and automatically regenerate embeddings. Microsoft SQL Server 2025 and Azure SQL provide several mechanisms to detect data changes, each with different tradeoffs in performance, scalability, complexity, and latency.

The exam focuses on selecting the most appropriate embedding maintenance strategy based on business requirements.


What Is Embedding Maintenance?

Embedding maintenance is the process of keeping vector embeddings synchronized with the underlying relational data.

Whenever data changes, one or more of the following actions may be required:

  • Generate a new embedding.
  • Replace the old embedding.
  • Update the vector index.
  • Remove deleted vectors.
  • Refresh search indexes.

Without proper maintenance, semantic search quality gradually degrades.


Why Embedding Maintenance Is Important

Suppose a product catalog contains this description:

“Wireless Bluetooth Noise-Cancelling Headphones”

An embedding is generated from that description.

Later, the product description changes to:

“Wireless Bluetooth Noise-Cancelling Headphones with Spatial Audio and USB-C Fast Charging”

If the embedding is not regenerated:

  • AI searches may not return the product.
  • Vector similarity decreases.
  • RAG answers become outdated.
  • Recommendation quality drops.

Keeping embeddings synchronized ensures AI applications remain accurate.


Common Embedding Maintenance Workflow

Most embedding maintenance solutions follow this lifecycle:

User Updates SQL Data
Change Detection
Generate New Embedding
Store Updated Vector
Refresh Vector Search Index

The primary difference between maintenance methods is how they detect changes.


Choosing the Right Maintenance Strategy

Microsoft provides several approaches:

MethodTypical LatencyComplexityBest For
Table TriggersImmediateLowSmall databases
Change TrackingLowMediumIncremental synchronization
Change Data Capture (CDC)MediumMediumETL and analytics
Azure Functions SQL TriggerNear real-timeMediumEvent-driven cloud apps
Azure Logic AppsNear real-timeLowLow-code automation
Change Event Streaming (CES)Real-timeHighStreaming architectures
Microsoft Foundry PipelinesScheduled or event-drivenMediumAI data pipelines

Table Triggers

What Are They?

Table triggers automatically execute SQL code whenever data changes.

Example events include:

  • INSERT
  • UPDATE
  • DELETE

Triggers provide immediate notification that data has changed.


Embedding Workflow Using Triggers

UPDATE Product
Trigger Executes
Identify Changed Row
Queue Embedding Job

The trigger usually should not generate the embedding itself because AI model inference may take several seconds.

Instead, the trigger inserts a work item into a processing queue.


Advantages

  • Immediate detection
  • Simple implementation
  • Works entirely within SQL
  • No polling required

Disadvantages

  • Can increase transaction duration
  • Poor choice for expensive AI operations
  • May reduce OLTP performance
  • Difficult to scale for very high transaction volumes

Best Practice

Use triggers only to record changes—not to call AI models directly.


Change Tracking

What Is Change Tracking?

Change Tracking is a lightweight SQL Server feature that records which rows have changed without recording every individual data modification.

Applications periodically retrieve changed rows and regenerate only affected embeddings.


Workflow

Application
Read Change Tracking
Changed Rows
Generate Embeddings
Update Vector Table

Advantages

  • Lightweight
  • Low storage overhead
  • Incremental processing
  • Excellent for synchronization

Limitations

  • Does not capture previous values
  • Does not store complete history
  • Requires periodic polling

Best Use Cases

  • RAG applications
  • Semantic search
  • Incremental embedding refresh
  • Azure SQL synchronization

Change Data Capture (CDC)

What Is CDC?

Change Data Capture records detailed information about every change made to a table.

It captures:

  • Inserts
  • Updates
  • Deletes
  • Previous values
  • New values
  • Log sequence numbers (LSNs)

CDC reads the SQL transaction log rather than relying on triggers.


Workflow

Transaction Log
CDC Tables
Embedding Pipeline
Vector Updates

Advantages

  • Complete history
  • High reliability
  • Efficient large-scale processing
  • Ideal for ETL

Disadvantages

  • More storage than Change Tracking
  • Higher administrative overhead
  • Not truly instantaneous

Best Use Cases

  • Enterprise ETL
  • Large databases
  • Historical auditing
  • Batch embedding refresh

Comparing Change Tracking and CDC

FeatureChange TrackingCDC
Tracks changed rowsYesYes
Stores previous valuesNoYes
Transaction log basedNoYes
Full historyNoYes
Storage overheadLowMedium
SynchronizationExcellentExcellent
AuditingLimitedExcellent

Azure Functions with SQL Trigger Binding

Azure Functions provide serverless compute that automatically executes code when SQL data changes.

Instead of polling SQL continuously, the SQL trigger binding reacts to data modifications.

Typical workflow:

SQL Change
Azure Function
Generate Embedding
Store Vector

Advantages

  • Serverless
  • Automatic scaling
  • Pay-per-execution
  • Near real-time processing
  • Excellent Azure integration

Best Use Cases

  • Cloud-native AI applications
  • Azure SQL Database
  • RAG systems
  • Intelligent search solutions

Azure Logic Apps

Azure Logic Apps provide a low-code workflow engine.

Instead of writing custom code, developers configure workflows visually.

Typical workflow:

SQL Change
Logic App Trigger
Call Azure OpenAI
Update Embedding Table

Advantages

  • Low-code development
  • Hundreds of built-in connectors
  • Easy integration with Azure services
  • Fast implementation

Limitations

  • Less flexible than custom code
  • Higher latency than Azure Functions
  • Complex workflows can become difficult to maintain

Best Use Cases

  • Business automation
  • Small AI workflows
  • Rapid prototyping
  • Citizen developers

Choosing Between Triggers, Change Tracking, CDC, Azure Functions, and Logic Apps

ScenarioRecommended Method
Small OLTP databaseTable Trigger + Queue
Incremental synchronizationChange Tracking
Historical auditingCDC
Serverless AI processingAzure Functions
Low-code workflowAzure Logic Apps

DP-800 Exam Tips (Part 1)

Remember these key points for the exam:

  • Triggers provide immediate notification but should not directly perform expensive AI inference.
  • Change Tracking records which rows changed and is optimized for lightweight synchronization.
  • CDC captures detailed change history and is ideal for enterprise ETL and auditing.
  • Azure Functions with SQL trigger binding enable scalable, serverless, event-driven embedding generation.
  • Azure Logic Apps offer a low-code approach for automating embedding workflows with Azure services.
  • Select the maintenance method based on the required balance of latency, scalability, operational complexity, and business requirements.

Go to the DP-800 Exam Prep Hub main page