Short answer: SQL Server 2025 vector search ranks records by comparing embeddings: numerical representations of text. Store document embeddings in a VECTOR column, generate a question embedding with the same model, and use VECTOR_DISTANCE() for exact similarity ranking. DiskANN indexing and VECTOR_SEARCH() are a separate preview path in SQL Server 2025.
This tutorial builds the database side of a semantic-search workflow in T-SQL. You'll configure an external embedding model, create a knowledge table, generate and store embeddings, run exact similarity searches, wrap the search in a stored procedure, split long text into chunks, and try approximate search with a DiskANN vector index. It returns matching passages from SQL Server. It doesn't build a web interface or send those passages to a language model.
The examples use OpenAI's text-embedding-3-small model, which produces 1,536 dimensions by default and fits the example's VECTOR(1536) column. See the OpenAI embeddings guide for the model’s configuration and input limits.
Feature support: SQL Server 2025 supports the VECTOR data type, VECTOR_DISTANCE(), CREATE EXTERNAL MODEL, and AI_GENERATE_EMBEDDINGS(). Microsoft Learn lists CREATE VECTOR INDEX and VECTOR_SEARCH() as preview features in SQL Server 2025, while they are generally available in Azure SQL Database. Index format version 3 is documented for the Azure services, so your instance may create an earlier format. Step 12 shows how to check.
Check your build before starting: Compare your instance with Microsoft’s SQL Server build history and choose the servicing update appropriate to your installation. GDR and cumulative-update servicing tracks differ. Recheck the feature documentation and known issues for your build, especially before trying preview vector indexes. The examples were reviewed against documentation; they were not executed on a SQL Server instance as part of this article review.
What Is SQL Server Vector Search?
SQL Server vector search retrieves information by comparing numerical representations of data. These representations are called vectors or embeddings.
A traditional search looks for matching words, values, or patterns. A user searching for "database backup" might miss a document that says "protecting SQL Server data with recovery copies", because the words differ. Semantic search tackles that. An embedding model turns text into a list of numbers that captures aspects of its meaning, and SQL Server measures the distance between those lists to find related content.
These three questions use different words but ask for nearly the same thing:
- How can I improve SQL Server query performance?
- How do I make a slow database query run faster?
- What are the best ways to optimize T-SQL execution?
An embedding model tends to place such phrases close together, and SQL Server ranks stored documents by that closeness.
Traditional search vs. semantic search
| Traditional keyword search | Semantic vector search |
|---|---|
| Looks for matching words or patterns | Compares numerical representations of meaning |
| Depends heavily on the wording used | Can find related content with different wording |
Uses LIKE or full-text search | Uses embeddings and distance calculations |
| Best for exact names, identifiers, and terms | Best for concept-based retrieval and AI applications |
Neither technique replaces the other. A production application can combine keyword search, relational filters, and vector similarity.
How Vector Search Works in SQL Server 2025
A vector search application has two workflows. During ingestion, an embedding model converts each passage into a vector and SQL Server stores both. At search time, the same model embeds the question. SQL Server compares that query vector with stored vectors and returns the closest passages. The illustration shows a question and a related passage using different words; it is a conceptual example, not measured search output.
During ingestion, the application generates an embedding for each piece of text and saves it next to the content. When a user searches, the same model creates a query vector, and SQL Server returns the closest stored vectors. The embedding model creates the vectors. SQL Server stores them and does the database-side search.
Prerequisites for SQL Server 2025 Vector Search
- Operating system: Windows for the SSMS-based steps here. SQL Server 2025 also runs on other platforms, but setup differs.
- Database engine: SQL Server 2025 (17.x), updated to a supported servicing release.
- Edition: Developer edition (Standard Developer or Enterprise Developer) for development and testing.
- SQL editor: SQL Server Management Studio (SSMS) 22 or later. You don't need Visual Studio. If you prefer another editor, the MSSQL extension for Visual Studio Code runs the same T-SQL.
- Embedding provider: An OpenAI API key with billing enabled, or another supported provider.
- Network access: Outbound HTTPS from the SQL Server host to the embedding endpoint.
- Knowledge: Basic tables,
SELECTstatements, and T-SQL.
SQL Server's default float32 vector format supports up to 1,998 dimensions, so VECTOR(1536) fits. The model's output dimensions and the column's dimensions must match exactly. See Microsoft's vector data type documentation.
Step 1: Install SQL Server 2025
If SQL Server 2025 is already installed, verify its version in Step 3 and continue from Step 2.
Download SQL Server 2025
- Open Microsoft's SQL Server downloads page.
- Choose SQL Server 2025 and select the free Developer edition.
- Download the installer and run
setup.exeas an administrator.
Configure the installation
- In SQL Server Installation Center, select Installation.
- Choose New SQL Server standalone installation or add features to an existing installation.
- Accept the license terms and continue.
- On Feature Selection, select Database Engine Services.
- Choose a default or named instance. A default instance is easiest, because you can connect with
localhost. - On Database Engine Configuration, choose Windows Authentication or Mixed Mode.
- Under SQL Server Administrators, select Add Current User.
- Review the summary and complete the installation.
When setup finishes, the summary page should show Database Engine Services as succeeded. For details, see Microsoft's installation wizard documentation.
Step 2: Install and Open SQL Server Management Studio
SSMS is the graphical tool you'll use to run every example.
- Open the SSMS release notes and download a supported generally available SSMS installer (SSMS 22 or a supported successor).
- Run the installer, then start SQL Server Management Studio from the Start menu.
- In the connection dialog, set the server type to Database Engine.
- For a default local instance, enter
localhostand choose Windows Authentication. For a named instance, uselocalhost\YourInstanceName(for example,localhost\SQLEXPRESS); use the instance name selected during setup. - If the dialog shows encryption options and your local instance uses a self-signed certificate, follow Microsoft's connection guidance. Don't disable encryption on a shared or production server.
- Click Connect.
When the connection succeeds, your server appears in Object Explorer.
Step 3: Open a Query Window and Verify the SQL Server Version
- In Object Explorer, right-click your server and choose New Query (or press
Ctrl+N). - Paste the query below, then click Execute (or press
F5).
SELECT
SERVERPROPERTY('ProductVersion') AS ProductVersion,
SERVERPROPERTY('ProductMajorVersion') AS ProductMajorVersion,
SERVERPROPERTY('Edition') AS Edition;
GO
SQL Server 2025 is the 17.x generation, so ProductMajorVersion should be 17 and ProductVersion should start with 17.0. Compare the full build with Microsoft’s build history. If the major version is different, you're connected to the wrong instance.
Before configuring a paid embedding endpoint, check the core vector operations with this deterministic three-dimensional fixture. It makes no network request and does not require a vector index. The expected cosine distances are approximately 0, 1, and 2; this is a mathematical checkpoint, not an execution result claimed by this review.
DECLARE @QueryVector VECTOR(3) = '[1,0,0]';
SELECT
sample.Label,
VECTOR_DISTANCE('cosine', sample.Embedding, @QueryVector) AS Distance
FROM
(
VALUES
(N'Same direction', CAST('[1,0,0]' AS VECTOR(3))),
(N'Perpendicular', CAST('[0,1,0]' AS VECTOR(3))),
(N'Opposite direction', CAST('[-1,0,0]' AS VECTOR(3)))
) AS sample(Label, Embedding)
ORDER BY Distance ASC;
GO
Step 4: Create a Database for Semantic Search
Use a new development database for this walkthrough. Database, table, credential, and model creation are one-time setup steps; rerunning them can produce “already exists” errors. Rerunning the sample inserts adds rows. Select only the intended query before pressing F5, and do not run the entire article as one script. The optional cloud and earlier-index examples are alternatives, not steps to execute together.
The example is a small SQL Server knowledge base. Each record has a title, a category, content, and an embedding. Create a database named KnowledgeSearchDb.
CREATE DATABASE KnowledgeSearchDb;
GO
USE KnowledgeSearchDb;
GO
Refresh Databases in Object Explorer. KnowledgeSearchDb should appear, and the toolbar's database drop-down should show it as active. If it doesn't, select it there, because every later step must run in this database.
Next, check the compatibility level. The chunking function in Step 8 needs level 170 or higher, and a new SQL Server 2025 database should already have it.
SELECT name, compatibility_level
FROM sys.databases
WHERE name = N'KnowledgeSearchDb';
GO
If the level is lower than 170, for example on a database restored from an older server, raise it with ALTER DATABASE KnowledgeSearchDb SET COMPATIBILITY_LEVEL = 170; after confirming your own workloads support it.
Step 5: Configure External Embedding Generation
A vector is a numerical representation of text. In this tutorial, an external OpenAI service computes it: CREATE EXTERNAL MODEL registers the endpoint, and AI_GENERATE_EMBEDDINGS() invokes it. SQL Server also has a separate local ONNX Runtime integration with additional Windows and Machine Learning Services prerequisites; it is outside this remote-provider walkthrough.
5.1 Enable external REST endpoint access
This feature is off by default. Enable it at the server level so SQL Server can call the embedding service.
EXECUTE sp_configure 'external rest endpoint enabled', 1;
RECONFIGURE WITH OVERRIDE;
GO
This needs administrative permission, including ALTER SETTINGS. Don't hand administrator rights to ordinary users to make development easier. The Messages tab should say the option changed, or that it was already set.
5.2 Create a database master key
The master key protects database-level secrets, including the credential used by the external model.
USE KnowledgeSearchDb;
GO
IF NOT EXISTS
(
SELECT 1
FROM sys.symmetric_keys
WHERE name = '##MS_DatabaseMasterKey##'
)
BEGIN
CREATE MASTER KEY ENCRYPTION BY PASSWORD = N'Replace_With_A_Strong_Unique_Password';
END;
GO
Replace the example password with a strong, unique secret. Keep it out of source control, and store it in your organization's secret manager.
5.3 Create an external model credential
The credential supplies HTTP authentication headers without putting an API key into every query. For OpenAI, use the Authorization header with a value beginning Bearer , as specified by OpenAI’s authentication reference. With HTTPEndpointHeaders, the credential secret is a flat JSON object of header names and values. The credential URL https://api.openai.com matches the protocol and host of https://api.openai.com/v1/embeddings and is broader than its path. The SQL Server host must be able to resolve and reach that trusted HTTPS endpoint. The cloud-service endpoint allowlist in Microsoft’s REST endpoint documentation applies to Azure SQL Database and Azure SQL Managed Instance; do not treat it as the same restriction on a self-managed SQL Server installation.
CREATE DATABASE SCOPED CREDENTIAL [https://api.openai.com]
WITH
IDENTITY = 'HTTPEndpointHeaders',
SECRET = '{"Authorization":"Bearer YOUR_OPENAI_API_KEY"}';
GO
Replace YOUR_OPENAI_API_KEY with your real key in a private session. Never paste a real key into an article, shared script, or repository. Restrict who can manage the credential, rotate the key by your organization's policy, and never print it while troubleshooting.
5.4 Register the OpenAI embedding model
CREATE EXTERNAL MODEL OpenAIEmbeddingModel
WITH
(
LOCATION = 'https://api.openai.com/v1/embeddings',
API_FORMAT = 'OpenAI',
MODEL_TYPE = EMBEDDINGS,
MODEL = 'text-embedding-3-small',
CREDENTIAL = [https://api.openai.com],
PARAMETERS = '{"dimensions":1536,"sql_rest_options":{"retry_count":3}}'
);
GO
LOCATIONis the embeddings endpoint. This remote provider requires HTTPS; local ONNX Runtime models use a different setup.API_FORMATnames the request format the provider expects.MODEL_TYPEmarks this as an embedding model.MODELselects the model that generates vectors.CREDENTIALpoints to the credential from Step 5.3.PARAMETERSpasses extra JSON to the request. Here it asks for 1,536 dimensions and tells SQL Server to retry temporary HTTP failures up to three times.retry_countaccepts a whole number from 0 to 10.
Confirm the model exists with SELECT * FROM sys.external_models;. You should see one row named OpenAIEmbeddingModel. SQL Server also supports Azure OpenAI, Ollama, and ONNX Runtime formats. Their endpoints and authentication differ, so see the CREATE EXTERNAL MODEL documentation.
5.5 Test the model call
Before building on the model, confirm that SQL Server can reach the endpoint and that the dimensions match.
DECLARE @TestEmbedding VECTOR(1536) =
AI_GENERATE_EMBEDDINGS(N'Hello from Codingvila' USE MODEL OpenAIEmbeddingModel);
SELECT @TestEmbedding AS TestEmbedding;
GO
You should get one cell holding a long list of numbers. An error here points to the endpoint, credential, permissions, or dimension setting, so fix it now (see the troubleshooting section).
5.6 Configure permissions for other users
Use an administrator for one-time setup, then a separate database user for normal use. Registering models requires CREATE EXTERNAL MODEL or ALTER ANY EXTERNAL MODEL; callers need EXECUTE on the model. The REST call path also requires the appropriate external-endpoint permission. The grants below illustrate the separate duties; replace YourDatabaseUser with a user created under your normal identity-management process. Do not grant model-creation permissions to a search-only application.
-- Only for users who must register their own models:
GRANT CREATE EXTERNAL MODEL TO [YourDatabaseUser];
GO
-- For users who generate embeddings:
GRANT EXECUTE ANY EXTERNAL ENDPOINT TO [YourDatabaseUser];
GO
GRANT EXECUTE ON EXTERNAL MODEL::OpenAIEmbeddingModel TO [YourDatabaseUser];
GO
Run these as a privileged administrator and follow least privilege in production. The embedding feature sends your text to the provider, so review the provider's privacy terms and your organization's data-handling rules before sending business or customer data.
The snippets contain placeholders, not working credentials. Configure real secrets privately during deployment, never in Blogger or a public repository. Model and REST permissions do not grant access to every table. If a caller invokes sp_invoke_external_rest_endpoint directly with a credential, Microsoft additionally documents REFERENCES permission on that database-scoped credential; that direct-REST permission path is distinct from executing an already registered model.
Step 6: Create a Table with the VECTOR Data Type
Now create the table that stores the records. VECTOR(1536) matches the model's dimensions.
CREATE TABLE dbo.KnowledgeChunks
(
ChunkId INT IDENTITY(1,1) PRIMARY KEY,
Title NVARCHAR(200) NOT NULL,
Category NVARCHAR(100) NOT NULL,
Content NVARCHAR(MAX) NOT NULL,
Embedding VECTOR(1536) NULL
);
GO
ChunkId: unique record ID. AnINTprimary key also meets the requirement of earlier vector-index formats (Step 12).Title: short name for the content.Category: lets you filter with ordinary SQL conditions.Content: the text to search semantically.Embedding: the vector generated from the title and content.
The vector column sits beside regular relational data. It can't be a primary or foreign key, so keep identifiers in ordinary columns.
Step 7: Insert Sample Knowledge-Base Records
Each Content value is built from short strings joined with +, so no stray line breaks or indentation end up in the text that gets embedded.
INSERT INTO dbo.KnowledgeChunks (Title, Category, Content)
VALUES
(
N'Create a Full SQL Server Backup', N'Backup',
N'Use the BACKUP DATABASE command to create a full backup of a SQL Server database. ' +
N'Store backups securely and verify that they can be restored when needed.'
),
(
N'Restore a SQL Server Database', N'Backup',
N'Use the RESTORE DATABASE command to recover a database from a valid backup file. ' +
N'Review recovery options and restore sequences before beginning a production recovery.'
),
(
N'Improve SQL Server Query Performance', N'Performance',
N'Use execution plans, Query Store, suitable indexes, and query analysis ' +
N'to investigate slow SQL Server queries.'
),
(
N'Create an Index in SQL Server', N'Performance',
N'Indexes can improve data retrieval by helping SQL Server locate rows efficiently. ' +
N'Review query patterns and index maintenance before adding new indexes.'
),
(
N'Prevent SQL Injection in Applications', N'Security',
N'Use parameterized queries and appropriate database permissions ' +
N'to protect applications against SQL injection attacks.'
),
(
N'Write a SQL Server Stored Procedure', N'TSQL',
N'Use CREATE PROCEDURE to define reusable database operations. ' +
N'Parameters allow applications to pass values into stored procedures safely.'
),
(
N'Configure SQL Server Connections', N'Configuration',
N'Use a suitable connection string, authentication configuration, server name, ' +
N'and database name when connecting an application to SQL Server.'
),
(
N'Understand SQL Server Transaction Management', N'TSQL',
N'Use transactions to group related database operations. ' +
N'COMMIT completes a transaction, while ROLLBACK reverses uncommitted changes.'
);
GO
SELECT ChunkId, Title, Category, Content
FROM dbo.KnowledgeChunks
ORDER BY ChunkId;
GO
You should see eight rows. Their Embedding values are still NULL, because you haven't generated vectors yet.
Step 8: Generate AI Embeddings Using T-SQL
AI_GENERATE_EMBEDDINGS() sends text to the registered model and returns a vector you can store in a VECTOR column. See the AI_GENERATE_EMBEDDINGS reference. This statement embeds each record's title and content together.
UPDATE kc
SET Embedding = AI_GENERATE_EMBEDDINGS
(
CONCAT(kc.Title, N'. ', kc.Content)
USE MODEL OpenAIEmbeddingModel
)
FROM dbo.KnowledgeChunks AS kc
WHERE kc.Embedding IS NULL;
GO
SELECT COUNT(*) AS TotalRecords, SUM(CASE WHEN Embedding IS NOT NULL THEN 1 ELSE 0 END) AS RecordsWithEmbeddings
FROM dbo.KnowledgeChunks;
GO
Embedding this update can generate a provider request for each qualifying row, with extra attempts when retries occur. Latency and billing depend on your provider, input, and rate limits; no execution time is promised. After a successful run on the fresh eight-row sample, both counts should be 8. If the statement errors, investigate the error and rows still missing embeddings before retrying. SQL rollback does not undo a remote request or its possible charge.
Embedding larger tables in batches
The loop below limits each update to a batch. Under normal autocommit behavior, each successful batch commits separately; a later failing batch does not undo earlier batches. An error aborts that update and can stop the loop—@MaxPasses limits successful passes, not retries after errors. It is a single-worker demonstration: a production ingestion worker also needs job state, concurrency control, bounded retries, and a source/model version so changed text is not left with an old vector.
DECLARE @BatchSize INT = 100;
DECLARE @Pass INT = 0;
DECLARE @MaxPasses INT = 1000;
WHILE @Pass < @MaxPasses
BEGIN
UPDATE TOP (@BatchSize) kc
SET Embedding = AI_GENERATE_EMBEDDINGS
(
CONCAT(kc.Title, N'. ', kc.Content)
USE MODEL OpenAIEmbeddingModel
)
FROM dbo.KnowledgeChunks AS kc
WHERE kc.Embedding IS NULL;
IF @@ROWCOUNT = 0 BREAK;
SET @Pass += 1;
END;
GO
Respect provider request and token limits. retry_count handles eligible temporary HTTP failures, not permanently invalid keys, unsupported dimensions, or oversized inputs. Fix persistent failures before rerunning. Embedding IS NULL skips previously populated rows only; it does not detect edited content. Avoid holding a large user transaction open while waiting for external model responses.
Chunking long documents
Each row above is a short, self-contained passage. For longer documents, split the text into chunks first so a search can point to the section that answers the question. AI_GENERATE_CHUNKS does this. It needs compatibility level 170 or higher and supports only fixed-size chunks measured in characters. OVERLAP is a whole-number percentage from 0 to 50.
This example stores one document, saves its 1,000-character chunks with 10 percent overlap, then embeds the saved chunks. Persisting text first leaves a clear work list if the provider call fails. The unique document/order key prevents duplicate positions for unchanged content; the tables and sample document insertion are still one-time setup steps, not a full concurrent ingestion service.
CREATE TABLE dbo.Documents
(
DocumentId INT IDENTITY(1,1) PRIMARY KEY,
Title NVARCHAR(200) NOT NULL,
Body NVARCHAR(MAX) NOT NULL
);
GO
CREATE TABLE dbo.DocumentChunks
(
DocumentChunkId INT IDENTITY(1,1) PRIMARY KEY,
DocumentId INT NOT NULL REFERENCES dbo.Documents (DocumentId),
ChunkOrder BIGINT NOT NULL,
ChunkText NVARCHAR(MAX) NOT NULL,
Embedding VECTOR(1536) NULL,
CONSTRAINT UQ_DocumentChunks_SourceOrder UNIQUE (DocumentId, ChunkOrder)
);
GO
-- Replace the Body value with your own long text.
INSERT INTO dbo.Documents (Title, Body)
VALUES (N'SQL Server maintenance notes', REPLICATE(CAST(N'Rebuild fragmented indexes, update statistics, and verify backups regularly. ' AS NVARCHAR(MAX)), 60));
GO
INSERT INTO dbo.DocumentChunks (DocumentId, ChunkOrder, ChunkText)
SELECT
d.DocumentId,
c.chunk_order,
c.chunk
FROM dbo.Documents AS d
CROSS APPLY AI_GENERATE_CHUNKS
(
SOURCE = d.Body,
CHUNK_TYPE = FIXED,
CHUNK_SIZE = 1000,
OVERLAP = 10
) AS c
WHERE NOT EXISTS
(
SELECT 1
FROM dbo.DocumentChunks AS existing
WHERE existing.DocumentId = d.DocumentId
AND existing.ChunkOrder = c.chunk_order
);
GO
UPDATE dc
SET Embedding = AI_GENERATE_EMBEDDINGS
(
dc.ChunkText USE MODEL OpenAIEmbeddingModel
)
FROM dbo.DocumentChunks AS dc
WHERE dc.Embedding IS NULL;
GO
SELECT DocumentId, ChunkOrder, LEN(ChunkText) AS ChunkLength
FROM dbo.DocumentChunks
ORDER BY DocumentId, ChunkOrder;
GO
The sample body repeats one maintenance sentence 60 times so it is long enough to split. Inspect the returned ChunkOrder and ChunkLength values to see the actual boundaries. Fixed-size chunks can cut a sentence or word in half, which is why overlap helps. Character counts are not token counts: check the embedding model’s tokenizer and input limit, not just LEN. If a document changes, version or replace its chunks and regenerate affected embeddings; the insert-only example does not automatically refresh edited documents. Test chunk sizes against real questions. Search saved chunks using the query below.
DECLARE @Question NVARCHAR(4000) = N'How should I protect database backups?';
DECLARE @QuestionEmbedding VECTOR(1536) =
AI_GENERATE_EMBEDDINGS(@Question USE MODEL OpenAIEmbeddingModel);
SELECT TOP (5)
d.DocumentId,
d.Title,
dc.ChunkOrder,
dc.ChunkText,
VECTOR_DISTANCE('cosine', dc.Embedding, @QuestionEmbedding) AS Distance
FROM dbo.DocumentChunks AS dc
INNER JOIN dbo.Documents AS d
ON d.DocumentId = dc.DocumentId
WHERE dc.Embedding IS NOT NULL
ORDER BY Distance ASC, dc.DocumentChunkId ASC;
GO
The results preserve DocumentId and ChunkOrder so you can retrieve the source passage or neighboring chunks. A repeated synthetic maintenance sentence is a chunking fixture, not a retrieval-quality benchmark. For production search, embed a consistent title-and-passage representation and apply the user’s document permissions as relational filters.
Step 9: Perform Exact Semantic Search with VECTOR_DISTANCE()
VECTOR_DISTANCE() calculates distance between two vectors without using a vector index. The query embeds the question once into a variable, then ranks the stored non-NULL vectors. Reusing that variable avoids embedding the same question inside the row comparison. See Microsoft’s VECTOR_DISTANCE reference and Codingvila’s T-SQL variable guide for the underlying syntax.
DECLARE @SearchText NVARCHAR(4000) =
N'How can I make slow SQL Server queries run faster?';
DECLARE @QueryEmbedding VECTOR(1536) =
AI_GENERATE_EMBEDDINGS(@SearchText USE MODEL OpenAIEmbeddingModel);
SELECT TOP (5)
kc.ChunkId,
kc.Title,
kc.Category,
kc.Content,
VECTOR_DISTANCE('cosine', kc.Embedding, @QueryEmbedding) AS Distance
FROM dbo.KnowledgeChunks AS kc
WHERE kc.Embedding IS NOT NULL
ORDER BY Distance ASC, kc.ChunkId ASC;
GO
The result contains up to five rows ordered by increasing cosine distance. Review whether the query-performance and indexing passages answer this question; their exact positions are not guaranteed. Exact nearest-neighbor search means exact ranking under the selected vector metric, not a guarantee that the embedding model understands the question correctly. Distance is not a confidence percentage: 0.15 does not mean “85% accurate.”
Understand Vector Distance Metrics
| Metric | Purpose | Interpretation |
|---|---|---|
cosine | Compares vector direction | Smaller distance means greater similarity |
euclidean | Measures straight-line distance | Zero means identical vectors |
dot | Uses the negative dot product | Smaller values mean greater similarity |
Cosine distance ranges from 0 (same direction) to 2 (opposite direction). It's a sensible starting point for text embeddings. Use the metric your embedding model recommends, and test it on your own data.
The same three directions from the earlier vector checkpoint explain cosine distance visually. The arrows below show direction only; they are not measured embeddings or retrieval results.
Step 10: Combine Vector Search with Relational Filters
10.1 Filter by category
Vector search is more useful when combined with ordinary conditions. This query searches only performance records.
DECLARE @SearchText NVARCHAR(4000) = N'How can I optimize slow T-SQL queries?';
DECLARE @QueryEmbedding VECTOR(1536) =
AI_GENERATE_EMBEDDINGS(@SearchText USE MODEL OpenAIEmbeddingModel);
SELECT TOP (5)
kc.ChunkId,
kc.Title,
kc.Category,
kc.Content,
VECTOR_DISTANCE('cosine', kc.Embedding, @QueryEmbedding) AS Distance
FROM dbo.KnowledgeChunks AS kc
WHERE kc.Category = N'Performance'
AND kc.Embedding IS NOT NULL
ORDER BY Distance ASC, kc.ChunkId ASC;
GO
With the sample data you should get the two performance records. The optimizer chooses the physical plan, so don't read the query text as a guarantee about the order of operations.
10.2 Wrap the search in a stored procedure
Pass the question as a typed stored-procedure parameter; do not concatenate it into executable SQL. With the shown dbo ownership arrangement, the application can be granted EXECUTE on the procedure rather than broad table permissions. This simple procedure does not automatically delegate external-model rights: the caller still needs the applicable model and endpoint permissions from Step 5.6. A signed module or carefully designed execution context is a separate security design when you want tighter delegation.
CREATE OR ALTER PROCEDURE dbo.SearchKnowledgeChunks
@SearchText NVARCHAR(4000),
@Category NVARCHAR(100) = NULL,
@TopN INT = 5
AS
BEGIN
SET NOCOUNT ON;
SET @SearchText = TRIM(
REPLACE(REPLACE(REPLACE(@SearchText,
NCHAR(9), N' '), NCHAR(10), N' '), NCHAR(13), N' '));
IF @SearchText IS NULL OR @SearchText = N''
THROW 50001, N'@SearchText is required.', 1;
IF @TopN IS NULL OR @TopN < 1 OR @TopN > 50
THROW 50002, N'@TopN must be between 1 and 50.', 1;
DECLARE @QueryEmbedding VECTOR(1536) =
AI_GENERATE_EMBEDDINGS(@SearchText USE MODEL OpenAIEmbeddingModel);
SELECT TOP (@TopN)
kc.ChunkId,
kc.Title,
kc.Category,
kc.Content,
VECTOR_DISTANCE('cosine', kc.Embedding, @QueryEmbedding) AS Distance
FROM dbo.KnowledgeChunks AS kc
WHERE kc.Embedding IS NOT NULL
AND (@Category IS NULL OR kc.Category = @Category)
ORDER BY Distance ASC, kc.ChunkId ASC;
END;
GO
EXECUTE dbo.SearchKnowledgeChunks
@SearchText = N'How do I protect my app from injection attacks?',
@Category = NULL,
@TopN = 3;
GO
Expect at most three rows. The SQL injection passage is a relevance candidate, not a promised first result. The procedure rejects empty or whitespace-only input and restricts @TopN to 1–50. Validate the 4,000-character query limit in the application before parameter binding; also honor the provider’s token limit. A category filter is not an authorization boundary—derive tenant/document access filters from the authenticated user before ranking private content.
Step 11: Enable Preview Features for the Optional Vector Index Lab
The exact VECTOR_DISTANCE() queries above do not require a vector index or preview configuration. You can finish here if exact search meets your needs.
To try Step 12 on SQL Server 2025, enable preview features only in the dedicated tutorial database. These commands do not make preview functionality production-ready.
USE KnowledgeSearchDb;
GO
ALTER DATABASE SCOPED CONFIGURATION SET PREVIEW_FEATURES = ON;
GO
Step 12 uses an indexed scratch table and labels the two approximate-query forms by index format. Consult the VECTOR_SEARCH reference for platform-specific behavior. The absence of WITH APPROXIMATE alone does not prove that a query is exact: earlier-format TOP_N queries are approximate too.
Step 12 (Optional, Preview): Try a DiskANN Vector Index
Exact search calculates a distance for every row, which gets expensive as a table grows. SQL Server 2025 offers DiskANN-based vector indexes for approximate nearest-neighbor search. An approximate index can reduce the search work on larger datasets, but speed depends on the workload and its results can differ from an exact search. Measure both latency and retrieval quality before choosing it.
Preview warning: Vector indexes and VECTOR_SEARCH() are preview features in SQL Server 2025, so behavior and limits can change. Test on a non-production database and review the SQL Server 2025 known issues before any production decision.
Match syntax to the index format. The examples distinguish version 3 from an earlier, deprecated format. Microsoft documents the version 3 format for Azure SQL Database, SQL database in Fabric, and Managed Instance with the Always-up-to-date update policy. Don't assume a boxed SQL Server 2025 installation can create it, because it may build the earlier format. Check the version first (Step 12.3), then use only the syntax that matches. If you're on a local install, expect option B. The comparison below summarizes the two syntax forms; use the version query in Step 12.3 to choose the applicable example.
| Behavior | Version 3 format | Earlier format |
|---|---|---|
| Approximate query syntax | SELECT TOP (N) WITH APPROXIMATE | TOP_N argument inside VECTOR_SEARCH() |
Filtering with WHERE | Applied during the search (iterative) | Applied after retrieval, so you can get fewer rows |
| Changing data after indexing | INSERT, UPDATE, DELETE, MERGE supported | Read-only unless you enable ALLOW_STALE_VECTOR_INDEX |
| Table requirement | At least 100 rows with non-NULL vectors | Clustered primary key on an int column, plus the 100-row minimum |
Your eight-row table is too small for an index, and creation fails with Msg 42266 below 100 rows. To practice without generating 100 provider embeddings, the lab uses a scratch table with 200 randomly generated five-dimension vectors. These are mock data. They show how the commands work, but they carry no meaning, so don't judge search quality with them.
12.1 Create the lab table
The lab uses GENERATE_SERIES, which needs compatibility level 160 or higher.
CREATE TABLE dbo.IndexLab
(
LabId INT IDENTITY(1,1) PRIMARY KEY,
Category NVARCHAR(50) NOT NULL,
Embedding VECTOR(5) NOT NULL
);
GO
INSERT INTO dbo.IndexLab (Category, Embedding)
SELECT
CASE WHEN s.value % 2 = 0 THEN N'Performance' ELSE N'Security' END,
CAST(JSON_ARRAY(
CAST((ABS(CHECKSUM(NEWID()) % 1000) + 1) / 1000.0 AS FLOAT),
CAST((ABS(CHECKSUM(NEWID()) % 1000) + 1) / 1000.0 AS FLOAT),
CAST((ABS(CHECKSUM(NEWID()) % 1000) + 1) / 1000.0 AS FLOAT),
CAST((ABS(CHECKSUM(NEWID()) % 1000) + 1) / 1000.0 AS FLOAT),
CAST((ABS(CHECKSUM(NEWID()) % 1000) + 1) / 1000.0 AS FLOAT)
) AS VECTOR(5))
FROM GENERATE_SERIES(1, 200) AS s;
GO
SELECT COUNT(*) AS RowsWithVectors FROM dbo.IndexLab WHERE Embedding IS NOT NULL;
GO
The last query should return 200.
12.2 Create the vector index
The index metric must match the metric you use in searches. If creation fails, read the actual error and check the active database, preview setting, permissions, row count, and feature support in your build. A syntax error alone does not identify the cause. Use a supported servicing update where appropriate, or stay with exact search.
CREATE VECTOR INDEX IX_IndexLab_Embedding
ON dbo.IndexLab (Embedding)
WITH
(
METRIC = 'cosine',
TYPE = 'DiskANN'
);
GO
This lab uses the DiskANN index type. If you already have an earlier-format index, consult Microsoft’s migration guidance and confirm the formats supported by your platform before replacing it. On your real table, create the index only after at least 100 rows have embeddings.
12.3 Check the index version
SELECT
i.name AS IndexName,
t.name AS TableName,
JSON_VALUE(v.build_parameters, '$.Version') AS IndexVersion
FROM sys.vector_indexes AS v
INNER JOIN sys.indexes AS i
ON v.object_id = i.object_id
AND v.index_id = i.index_id
INNER JOIN sys.tables AS t
ON v.object_id = t.object_id
WHERE t.object_id = OBJECT_ID(N'dbo.IndexLab');
GO
Use option A only when IndexVersion is 3 and your platform supports that format. Use option B for a reported earlier format supported by your build. If the version is NULL, unrecognized, or no row is returned, stop and check the catalog and platform documentation instead of guessing a syntax branch. On the version 3 format you can also watch background maintenance with sys.dm_db_vector_indexes. See the CREATE VECTOR INDEX documentation for migration steps.
12.4 Run an approximate search
Option A: version 3 format. Use SELECT TOP (N) WITH APPROXIMATE. The older TOP_N argument fails with Msg 42274 on version 3 indexes.
DECLARE @QueryVector VECTOR(5) = '[0.5, 0.5, 0.5, 0.5, 0.5]';
SELECT TOP (5) WITH APPROXIMATE
lab.LabId,
lab.Category,
searchResult.distance
FROM VECTOR_SEARCH
(
TABLE = dbo.IndexLab AS lab,
COLUMN = Embedding,
SIMILAR_TO = @QueryVector,
METRIC = 'cosine'
) AS searchResult
ORDER BY searchResult.distance ASC;
GO
Expect up to five rows ordered by distance. Recreating and repopulating the lab generates different vectors; rerunning a search against unchanged rows does not regenerate them. Approximate retrieval can also differ from the exact baseline. With WITH APPROXIMATE, the ORDER BY must exist and reference only distance in ascending order. Extra sort columns or DESC fail with Msg 42271, and a missing ORDER BY fails with Msg 42248. For extra sorting, wrap the approximate query in a subquery and sort in the outer query.
Option B: earlier format. Pass the row count as TOP_N and leave out WITH APPROXIMATE.
DECLARE @QueryVector VECTOR(5) = '[0.5, 0.5, 0.5, 0.5, 0.5]';
SELECT TOP (5)
lab.LabId,
lab.Category,
searchResult.distance
FROM VECTOR_SEARCH
(
TABLE = dbo.IndexLab AS lab,
COLUMN = Embedding,
SIMILAR_TO = @QueryVector,
METRIC = 'cosine',
TOP_N = 5
) AS searchResult
ORDER BY searchResult.distance ASC;
GO
12.5 Filter approximate results
With the version 3 format, a WHERE filter guides which neighbors the search visits, so you still get the number of rows you asked for when enough of them qualify. The earlier format fetches its nearest rows first and filters afterward, which can leave you with a short result. On option B, request more rows through TOP_N than you need and trim the list yourself.
-- Version 3 format only
DECLARE @QueryVector VECTOR(5) = '[0.5, 0.5, 0.5, 0.5, 0.5]';
SELECT TOP (5) WITH APPROXIMATE
lab.LabId,
lab.Category,
searchResult.distance
FROM VECTOR_SEARCH
(
TABLE = dbo.IndexLab AS lab,
COLUMN = Embedding,
SIMILAR_TO = @QueryVector,
METRIC = 'cosine'
) AS searchResult
WHERE lab.Category = N'Performance'
ORDER BY searchResult.distance ASC;
GO
Every returned row should have the category Performance. On a real table, a regular index on the filter column can help the search apply the filter efficiently. Microsoft documents the FORCE_ANN_ONLY table hint, which forces use of the vector index, for the Azure SQL services. Check the current platform notes before using it on SQL Server 2025, because it may not be available there.
For the earlier-format index on a boxed SQL Server installation, the following query requests 20 candidates before returning up to five Performance rows. Oversampling reduces short result sets but does not guarantee five eligible matches. Adjust candidate counts only after measuring recall and latency on the real workload.
-- Earlier-format vector index only: oversample before post-filtering
DECLARE @QueryVector VECTOR(5) = '[0.5,0.5,0.5,0.5,0.5]';
SELECT TOP (5)
lab.LabId,
lab.Category,
result.distance
FROM VECTOR_SEARCH
(
TABLE = dbo.IndexLab AS lab,
COLUMN = Embedding,
SIMILAR_TO = @QueryVector,
METRIC = 'cosine',
TOP_N = 20
) AS result
WHERE lab.Category = N'Performance'
ORDER BY result.distance ASC;
GO
12.6 Clean up the lab
IF OBJECT_ID(N'dbo.IndexLab', N'U') IS NOT NULL
BEGIN
DROP INDEX IF EXISTS IX_IndexLab_Embedding ON dbo.IndexLab;
DROP TABLE dbo.IndexLab;
END;
GO
Exact Search vs. Approximate Search
| Comparison | Exact search | Approximate search |
|---|---|---|
| Function | VECTOR_DISTANCE() in this walkthrough | VECTOR_SEARCH() with a vector index |
| Result | Exact distance ranking | Approximate nearest neighbors |
| Vector index | VECTOR_DISTANCE() never uses one | Can use DiskANN |
| Status in SQL Server 2025 | VECTOR_DISTANCE() is generally available | Preview |
| Best for | Smaller datasets and exact ranking needs | Larger datasets where approximate retrieval is acceptable |
For a small database, exact search is a straightforward start. As data grows, benchmark approximate search on your own workload and measure both retrieval quality and resource use.
Best Practices for SQL Server Vector Search
1. Use the same embedding model for documents and queries
Embed stored content and user questions with the same model and dimension settings. Mixing models or dimensions causes errors or unreliable results.
2. Choose document chunks carefully
Don't embed a whole large document as one record. Split it into coherent passages so a search can find a specific section, and evaluate retrieval with real questions. No single chunk size suits every application.
3. Keep embeddings synchronized with the source data
When content changes, regenerate its embedding, and record which model and dimensions produced each vector. For an earlier-format index, follow its documented refresh/rebuild requirements after data changes. Version 3 indexes maintain indexed data as it changes. When changing models, populate a separate column or table, evaluate it, and create a compatible index before switching searches.
4. Avoid unnecessary API requests
Generate document embeddings when the represented content or model changes. For text searches, reuse an appropriate cached query embedding when available; an uncached question needs its own vector. Keep model, dimensions, preprocessing, and permissions consistent with any cache key. Never reuse a cached result across users with different document access.
5. Secure external model access
Protect credentials and grant narrowly scoped table, procedure, model, and endpoint permissions for the actual execution path. Granting EXECUTE on a procedure alone does not necessarily authorize the external model it calls. Review provider data-handling terms before sending private content. Apply document/tenant authorization inside retrieval; similarity alone must not determine access.
6. Evaluate retrieval quality
A small distance doesn't guarantee a helpful result. Write a set of realistic questions and check whether the returned passages actually answer them. Remove near-identical passages before indexing, because repeats take up result slots that better matches should have.
7. Test preview features separately
Vector indexes and approximate search are preview features in SQL Server 2025. Review Microsoft's release information and known issues before using them in production.
Common SQL Server Vector Search Errors and Solutions
Error 1: Invalid vector dimension
The model returned a different number of dimensions than the column or variable declares. Solution: make the column, the query variable, and the model's dimensions parameter agree.
Error 2: External endpoint invocation is disabled
The embedding call fails when external REST endpoint access is off or the caller lacks permission. Solution: check that external rest endpoint enabled is 1, then review the user's EXECUTE ANY EXTERNAL ENDPOINT and model EXECUTE permissions.
Error 3: Credential or authentication fails
Check credential URL matching, the real HTTP authentication header, provider access, permissions, and connectivity from the SQL Server host. OpenAI expects Authorization: Bearer .... HTTP 401 commonly points to authentication; HTTP 429 can indicate rate or quota limits. Do not print secrets or repeatedly retry an invalid key. On Azure SQL platforms, additionally check their endpoint allowlist; this is not the same platform rule as self-managed SQL Server.
Error 4: Syntax error on VECTOR_SEARCH or CREATE VECTOR INDEX
The preview feature isn't enabled, or your build doesn't include it or uses the older syntax. Solution: run ALTER DATABASE SCOPED CONFIGURATION SET PREVIEW_FEATURES = ON; in the correct database, check your build against Microsoft's build history, and apply a supported cumulative update appropriate to your servicing track. If it still fails, use the earlier-index TOP_N example from Step 12 only when your index format supports it, or stay with the exact VECTOR_DISTANCE() query in Step 9. Changing syntax does not make approximate retrieval exact.
Error 5: Msg 42266, too few rows for a vector index
Vector indexes need at least 100 rows with non-NULL vectors. Solution: load at least 100 rows with valid embeddings first, or use the mock-vector lab in Step 12.
Error 6: Msg 42274, outdated TOP_N syntax
TOP_N isn't supported with version 3 indexes. Solution: remove it and use SELECT TOP (N) WITH APPROXIMATE. With an earlier-format index, TOP_N is the correct form.
Error 7: Msg 42271 or 42248, invalid ORDER BY with WITH APPROXIMATE
The query sorts by an extra column, sorts descending, or has no ORDER BY. Solution: order only by distance, ascending, and do any extra sorting in an outer query.
Error 8: Data changes fail on a table with a vector index
An earlier-format index makes the table read-only. Solution: load data before indexing, drop and recreate the index so it uses the version 3 format if your build supports it, or review ALLOW_STALE_VECTOR_INDEX if you can tolerate stale search results.
Error 9: AI_GENERATE_CHUNKS can't be found
Confirm that you are connected to SQL Server 2025 in the intended database. A compatibility level below 170 prevents the engine from finding this function. Solution: check the server version and the Step 4 result; raise compatibility only after confirming your workloads support it. An older SQL Server engine cannot gain this function through a compatibility change.
SQL Server Vector Search: Important Limitations
- Dimensions: The default
float32format supports up to 1,998 dimensions. Check Microsoft's vector data type page for other precisions and their status. - Preview status: Vector indexes and
VECTOR_SEARCH()remain preview features in SQL Server 2025. - Index format: The version 3 format may not be available on your instance. The earlier format has a read-only table, post-filtering, the
TOP_Nargument, and anintclustered primary key requirement. - Minimum data: Index creation needs at least 100 rows with non-
NULLvectors. - Index operations: Partitioning and replication to subscribers aren't available for vector indexes.
TRUNCATE TABLEis blocked while the index exists, so to empty the table, drop the index, truncate, reload at least 100 rows, then recreate the index. - Deployment: DacFx deployment behavior depends on its version and the loaded data. Microsoft documents BACPAC support from DacFx 170.5.96; schema-only deployment can skip a vector index when too few populated vectors exist. Load enough data, create or republish the index as appropriate, then verify
sys.vector_indexesrather than assuming deployment created it. - Views:
VECTOR_SEARCH()can't be used in a view body. - Client drivers: Applications need a driver and protocol version that support the vector type to read and write vectors natively. Older clients see vectors as JSON text. Check your driver's documentation.
- External model dependency: This OpenAI walkthrough needs HTTPS connectivity, credentials, provider availability, and permission to call the model. Precomputed vectors and the separate ONNX integration have different dependencies.
- Data privacy: Text passed to
AI_GENERATE_EMBEDDINGS()is sent to the configured endpoint. - Data freshness: Changing source text without regenerating its embedding gives outdated results.
The VECTOR type also has table restrictions. Vector columns can't be primary or foreign keys, can't have DEFAULT or CHECK constraints, can't be used in memory-optimized tables or with Always Encrypted, and can't have B-tree or columnstore indexes (though they can be included columns). The type doesn't support comparison, arithmetic, or concatenation operators. Keep identifiers and filter fields in ordinary columns.
When Should You Use SQL Server Vector Search?
It fits well when your important relational data already lives in SQL Server and you want semantic retrieval without moving it to a separate database. Typical uses:
- Technical documentation search: find relevant docs from natural-language questions.
- Customer support knowledge bases: retrieve troubleshooting articles that match the problem a customer describes.
- Product discovery: surface products whose descriptions relate to a user's interests.
- Enterprise document search: retrieve passages from stored company documents.
- Retrieval-augmented generation (RAG): retrieve database content that an external language model uses as context.
A dedicated vector database may suit some workloads better, depending on scale, latency, operations, and features. Weigh the trade-offs instead of assuming one technology fits everything.
Frequently Asked Questions
1. Does SQL Server 2025 support vector search?
Yes. It supports the native VECTOR type and exact operations such as VECTOR_DISTANCE(). Vector indexing and VECTOR_SEARCH() are preview features.
2. What is the VECTOR data type in SQL Server 2025?
It stores numerical vectors for similarity search and machine learning. You declare the dimensions when you define the column or variable.
3. What is the difference between VECTOR_DISTANCE and VECTOR_SEARCH?
VECTOR_DISTANCE() calculates an exact distance between two vectors. VECTOR_SEARCH() finds nearest neighbors and can use an approximate vector index.
4. Does SQL Server generate AI embeddings automatically?
It provides AI_GENERATE_EMBEDDINGS() to invoke a registered embedding model. The remote OpenAI example sends text over HTTPS. Local ONNX Runtime integration is a separate Windows setup requiring Machine Learning Services and its documented runtime prerequisites; it is not enabled merely by pointing the HTTP example at a local folder.
5. What embedding model can I use with SQL Server?
Microsoft documents OpenAI, Azure OpenAI, Ollama, and ONNX Runtime formats, subject to each provider's API and configuration requirements.
6. Is SQL Server vector search suitable for RAG applications?
Yes, for the retrieval half. SQL Server can store embeddings and return relevant content. Generating the final answer needs a separate language model or application component.
7. Do I need a vector index to use VECTOR_DISTANCE?
No. VECTOR_DISTANCE() works without an index, which suits smaller datasets and first implementations.
8. Are SQL Server 2025 vector indexes production-ready?
Microsoft lists them as preview in SQL Server 2025 and generally available in Azure SQL Database. Review the current documentation and known issues before adopting them in production on SQL Server 2025.
9. How many rows do I need before creating a vector index?
At least 100 rows with non-NULL vectors. With fewer, creation fails with Msg 42266. Exact search works at any size.
10. Can I use SQL Server vector search without OpenAI?
Yes. You can supply precomputed embeddings or use another documented provider, such as Azure OpenAI or a correctly configured Ollama endpoint. A local ONNX Runtime model uses the separate runtime integration. The document and query embeddings must use a compatible model and the same dimensions and preprocessing.
11. Can I use this native VECTOR tutorial on SQL Server 2022?
No. This walkthrough targets SQL Server 2025 (17.x). SQL Server 2022 does not acquire the native VECTOR type or these functions by changing a compatibility setting. Older-server solutions that store JSON or binary embeddings and calculate similarity in application code are different implementations.
12. Is SQL Server semantic search the same as full-text search?
No. Full-text search works with indexed language terms and its own ranking rules; vector retrieval compares embeddings. Neither proves that a passage is relevant or factual. Use ordinary predicates for exact IDs, permissions, dates, and numeric ranges. A combined keyword/vector retrieval system needs its own ranking and evaluation design.
13. How do I measure vector-search quality?
Build a small evaluation set of real questions with relevant document IDs labeled by a reviewer. Check the exact top-k results first. Then compare approximate top-k IDs with that baseline using recall@k (the fraction of baseline neighbors retrieved), while separately checking whether the passages answer each question. Measure latency and resource use on representative data; a fixed row-count cutoff or low cosine distance is not a quality guarantee.
14. What changes when documents or embedding models change?
Regenerate vectors when the text representation changes. Record the model identifier, dimensions, preprocessing version, and source version or hash. Migrate to a different model in a separate column or table and validate it before switching searches; equal dimensions alone do not make two embedding spaces compatible. Rebuild an earlier-format vector index when needed, and follow the update behavior documented for your actual index format.
Conclusion
SQL Server 2025 vector search adds semantic retrieval to the relational engine. The VECTOR type, VECTOR_DISTANCE(), and external-model integration let you store embeddings beside your application data and retrieve passages by meaning.
In this tutorial you created a knowledge-base table, registered and tested an external embedding model, generated document and query embeddings, ran exact similarity searches, wrapped the search in a stored procedure, and split long text into chunks. You also practiced creating a DiskANN vector index and checking its version, which remain preview features in SQL Server 2025.
Start with exact search and a set of real test questions. Add an approximate index only when the dataset justifies it, the table meets the 100-row minimum, and your measurements show that quality and performance are acceptable.

