Find the Nearest Chunks with SQL

Once every passage of a set of documents is stored in PostgreSQL beside its embedding, finding the passages that bear on a question takes one SQL query. The query measures how far each stored vector is from the question's vector and keeps the few closest. Getting it right means choosing how distance is measured, reading the numbers it returns the right way round, and knowing when a large table needs a faster, approximate way to search.

The nearest rows to a question

An embedding places a text as a point in a space with hundreds of dimensions, so that texts with similar meaning sit close together. A question, embedded by the same model, becomes one more point in that space. The passages most likely to answer it are the points nearest to it: its nearest neighbours.

The picture below flattens the idea to two dimensions. Each grey dot is a stored passage, the accent dot is the question, and the dashed circle holds the three passages closest to it. Asking for the nearest neighbours with k = 3 means exactly this: rank every passage by its distance to the question and keep the first three.

  • k = 3
  • question
  • 1st
  • 2nd
  • 3rd

In SQL the same idea needs no new keywords. ORDER BY sorts the rows by an expression, here the distance between the stored vector and the question vector, from smallest to largest. LIMIT keeps the first k rows of that order. pgvector supplies the distance as an operator written between the two vectors:

SELECT id, heading, embedding <=> '[0.12, -0.40, 0.33]' AS distance
FROM chunks
ORDER BY embedding <=> '[0.12, -0.40, 0.33]'
LIMIT 3;

The vector in quotes stands for the question's embedding; a real one has as many numbers as the column's dimension. The operator appears twice: in ORDER BY it ranks the rows, and in the select list it returns each row's distance as a column, so the result shows how close every passage is. From Python the question vector is not pasted into the text. It travels as a parameter, the same way as any other value, once the pgvector adapter is registered on the connection:

rows = conn.execute(
    """
    SELECT id, heading, embedding <=> %(q)s AS distance
    FROM chunks
    ORDER BY embedding <=> %(q)s
    LIMIT 3
    """,
    {"q": question_vector},
).fetchall()

One property of this query matters later: it always returns k rows when the table holds at least k. Nothing in it says how close a row has to be. If no stored passage is about the question at all, the query still returns the three least distant ones, and only their distances reveal that they are far away.

True or false?

If no passage in the table is about the question, a query with ORDER BY distance and LIMIT 3 returns no rows.

False. The query ranks every row and keeps the first three, however far they are. Only a WHERE condition on the distance would leave rows out.

The question must be embedded by the same model as the stored passages for the distances to mean anything.

True. Each model places texts in its own space. A distance between points from two different models compares coordinates that do not correspond.

Distance, not similarity

Cosine similarity measures the angle between two vectors: 1 when they point the same way, 0 when they are at a right angle, -1 when they point in opposite directions. A higher similarity means a closer meaning. pgvector's cosine operator <=> does not return that number. It returns the cosine distance, which is one minus the similarity:

$$d_{\cos}(a, b) = 1 - \frac{a \cdot b}{\lVert a \rVert \, \lVert b \rVert} = 1 - \text{cosine similarity}$$

Cosine distance

Subtracting from one turns the scale around, so the smallest distance is the closest meaning. That is the direction a nearest-neighbour query needs, because ORDER BY sorts from the smallest value up.

The two vectors pointCosine similarityCosine distance
the same way10
at a right angle01
in opposite directions-12

When a similarity is easier to read, compute it in the select list as 1 - (embedding <=> q), and keep ordering by the distance itself. Sorting by 1 - (embedding <=> q) DESC would give the same rows today, while every row is compared. The difference appears once the table has a vector index, a structure that speeds up the search on large tables: PostgreSQL uses it only when ORDER BY is the distance operator in ascending order. Ordering by the distance from the start keeps a query ready for an index.

SELECT heading, 1 - (embedding <=> '[0.12, -0.40, 0.33]') AS similarity
FROM chunks
ORDER BY embedding <=> '[0.12, -0.40, 0.33]'
LIMIT 3;

True or false?

A row with cosine distance 0.15 is closer in meaning to the question than a row with cosine distance 0.60.

True. Cosine distance is one minus the similarity, so 0.15 is a similarity of 0.85 and 0.60 a similarity of 0.40.

Because <=> measures cosine, a nearest-neighbour query should sort its result with ORDER BY ... DESC.

False. The operator returns a distance, where smaller is closer. Ascending order, the default, puts the nearest rows first.

Three operators for three ways to compare

pgvector has an operator for each common way of comparing vectors. The three below are the ones embeddings are usually compared with; pgvector also has <+> for L1 (taxicab) distance, and <~> and <%> for binary vectors. All of them return a distance, so for all of them a smaller value means closer and the nearest rows come first in ascending order.

OperatorWhat it returnsVector length counts?
<=>cosine distance: 1 minus cosine similarityno, only the angle
<->Euclidean (L2) distance: the straight-line distance between the pointsyes
<#>negative inner product: the dot product times -1yes

The inner product operator needs a word of its own. A larger inner product means more similar vectors, so sorting by it from the smallest value up would put the least similar rows first. Descending order is no way out, because PostgreSQL can use an index for an operator only in ascending order. So <#> returns the inner product with its sign flipped: the most similar row has the most negative value and comes first. To show the inner product itself, multiply by -1 in the select list: (embedding <#> q) * -1.

True or false?

With <#>, the row that comes first in ORDER BY ascending has the largest inner product with the question.

True. The operator returns the inner product times -1, so the largest inner product becomes the most negative value, which sorts first.

Choosing the operator

The right operator is the one the embedding model was meant to be compared with. A model is trained so that one particular measure, usually cosine similarity, reflects closeness of meaning, and that measure is part of the model's description. In the Sentence Transformers library, for example, a model can declare its similarity function as cosine, dot product or Euclidean, and cosine is used when it declares none.

Whether the vectors are normalised, scaled to length one, also matters. For vectors of length one the three operators agree on the order. Cosine distance becomes one minus the dot product, and the squared Euclidean distance becomes two minus twice the dot product:

$$\lVert a \rVert = \lVert b \rVert = 1 \;\Rightarrow\; d_{\cos}(a, b) = 1 - a \cdot b$$

Cosine distance for unit vectors

$$\lVert a - b \rVert^2 = 2 - 2\, a \cdot b$$

Squared Euclidean distance for unit vectors

Each value is a different number, but each grows as the dot product shrinks, so all three rank the rows identically. For normalised vectors the pgvector documentation recommends the inner product for the best performance, since it skips the division by the two lengths. Normalised output is not automatic, though: Sentence Transformers' encode returns unit vectors only when the model ends with a normalisation step or when it is called with normalize_embeddings=True.

When the vectors are not normalised, the operators disagree. The inner product rewards long vectors and Euclidean distance penalises vectors of different lengths, even when they point the same way; cosine distance looks only at the direction. For a model meant to be compared by cosine similarity, <=> is the operator that gives the ranking the model was trained for, whatever the vectors' length.

True or false?

If every stored vector and the question vector have length one, ordering by <=>, <-> or <#> returns the same rows in the same order.

True. For unit vectors all three distances are functions of the dot product that grow as it shrinks, so the order is the same even though the values differ.

The operator can be chosen freely, because every distance ranks rows the same way.

False. That holds only for unit-length vectors. For vectors of different lengths, the inner product and Euclidean distance mix length into the ranking, so the order can change.

Approximate indexes for large tables

When a table holds millions of vectors, measuring every row for every question takes too long. A vector index avoids it by organising the vectors in advance so that a search can look at only part of the data: the part most likely to hold the nearest rows. This is approximate nearest-neighbour search. It answers faster, and in exchange it may miss some of the true nearest rows, because a row in the part it skipped is never measured.

pgvector offers two index types, and each skips data in its own way:

  • IVFFlat divides the vectors into groups called lists, each around a centre point. A search measures the question against the list centres and then reads only the rows in the closest lists. By default it reads one list (ivfflat.probes = 1).
  • HNSW builds a graph with several layers that links each vector to some of its near neighbours. A search starts at an entry point and walks along the links towards the question, measuring only the vectors it passes on the way.

The picture shows how an IVFFlat search with one list can miss. The question lies near the edge of its list. The closest passage of all sits just across the border, in a list the search never reads, so the search returns the best row of its own list instead.

  • list searched
  • list skipped
  • question
  • true nearest, missed
  • returned

This is why the pgvector documentation warns that, unlike ordinary database indexes, an approximate index changes the results of queries once it is added. An ordinary index, such as a B-tree on a column of numbers, finds exactly the rows a full scan would find, only faster. A vector index finds most of them.

Each index type has a setting that trades some of the speed back for recall. For IVFFlat, ivfflat.probes sets how many lists are read. For HNSW, hnsw.ef_search (40 by default) sets how many candidates the search keeps as it walks the graph. Raising either reads more of the data, so the search finds more of the true nearest rows and takes longer.

The two index types
HNSWIVFFlat
Structurea layered graph of neighbourslists of vectors around centre points
Speed for the same recallbetterlower
Build time and memoryslower to build, more memoryfaster to build, less memory
On an empty tablecan be created before any datacreate it after the table has data
Recall settinghnsw.ef_search (default 40)ivfflat.probes (default 1)

An index is built for one distance, named by its operator class, and serves only queries that use that distance's operator. An index created with vector_cosine_ops serves <=>; vector_l2_ops serves <-> and vector_ip_ops serves <#>. The query itself does not change: the same ORDER BY on the operator, ascending, with a LIMIT, and PostgreSQL decides whether to use the index.

CREATE INDEX ON chunks USING hnsw (embedding vector_cosine_ops);

When a table needs one

A table needs a vector index when exact search has become too slow for the application and a small chance of missing a near row is acceptable in return. Until then an index only adds a way to get different answers: on a small table the scan is fast, its results are exact, and PostgreSQL may ignore an index there anyway because reading every row costs less than using it.

True or false?

Adding an HNSW index to a vector column makes the same queries faster but leaves their results unchanged, like a B-tree index.

False. An approximate index reads only part of the data, so it can miss some of the true nearest rows. Results can differ after it is added.

An index created with vector_cosine_ops is not used by a query that orders by <->.

True. Each index serves the operator of its operator class. A query ordering by Euclidean distance needs an index built with vector_l2_ops.

Any table with a vector column should have a vector index, because a query without one compares the question with every row.

False. On a small table comparing every row is fast and exact, and a table scan may even be faster than the index. An index pays off when the table is too large for exact search to answer in time.