// math reference

SQL VECTOR_DISTANCE function

Embedding search ranks rows by how close their vectors are to a query vector. SQL Server 2025 and Oracle 23ai do this with a built-in VECTOR_DISTANCE.

Category
Math
Returns
float
In this category
82 of 82

Syntax

VECTOR_DISTANCE('metric', v1, v2)  -- SQL Server
VECTOR_DISTANCE(v1, v2, METRIC)  -- Oracle

Each block is a separate form. The support table and the examples show which engine takes which.

Engine support

EngineSupportNotes
SQL Server Yes VECTOR_DISTANCE('cosine' | 'euclidean' | 'dot', v1, v2) on 2025
PostgreSQL Not built in not built in; the pgvector extension adds <=> (cosine), <-> (Euclidean) and <#> (negative inner product)
MySQL Not built in no vector functions in 8.4
SQLite Not built in not built in; extensions such as sqlite-vec
Oracle Yes VECTOR_DISTANCE(v1, v2, COSINE), plus COSINE_DISTANCE and L2_DISTANCE, 23ai+

Examples

SQL Server

SELECT VECTOR_DISTANCE('cosine', CAST('[1,0]' AS VECTOR(2)), CAST('[0,1]' AS VECTOR(2))) AS cos_d,
       VECTOR_DISTANCE('euclidean', CAST('[0,0]' AS VECTOR(2)), CAST('[3,4]' AS VECTOR(2))) AS l2;  -- 1.0, 5.0

Oracle

SELECT VECTOR_DISTANCE(TO_VECTOR('[1,0]'), TO_VECTOR('[0,1]'), COSINE) AS cos_d,
       VECTOR_DISTANCE(TO_VECTOR('[0,0]'), TO_VECTOR('[3,4]'), EUCLIDEAN) AS l2
FROM dual;  -- 1, 5

SQL Server

SELECT VECTOR_DISTANCE('dot', CAST('[1,2]' AS VECTOR(2)), CAST('[3,4]' AS VECTOR(2))) AS neg_dot;  -- -11.0

Good to know

  • The argument order differs: SQL Server puts the metric first as a string, VECTOR_DISTANCE('cosine', a, b); Oracle puts it last as a keyword, VECTOR_DISTANCE(a, b, COSINE).
  • Cosine distance is 1 minus cosine similarity: 0 means the same direction and 1 means orthogonal. Sort ascending to get the nearest rows.
  • SQL Server's 'dot' metric returns the negative dot product, so smaller still means closer: [1,2] and [3,4] give -11.
  • Both vectors must have the same number of dimensions; SQL Server raises error 42204 otherwise.

Questions about VECTOR_DISTANCE

Does ORDER BY VECTOR_DISTANCE use an index?

No, it computes the distance for every row. Oracle 23ai adds vector indexes used through FETCH APPROX FIRST n ROWS ONLY, and SQL Server 2025 has a separate VECTOR_SEARCH function (in preview) for approximate search over a vector index.

Which metric should I use?

The one the embedding model was trained for, which is usually cosine. For vectors normalized to length 1, cosine and dot product give the same ranking.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: SQL Server, Oracle.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.