Sub topic 7
Exact nearest-neighbor queries with ORDER BY and LIMIT
This chapter assumes you can write basic SQL, have pgvector enabled, and have a table with a vector column like the one built earlier. The examples use this table:
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE items (
id bigserial PRIMARY KEY,
content text NOT NULL,
embedding vector(3)
);
INSERT INTO items (content, embedding) VALUES
('a', '[1,2,3]'),
('b', '[4,5,6]'),
('c', '[1,1,1]');The query pattern
A nearest-neighbor query in pgvector is an ordinary SELECT. You compute the distance between each row's vector and a query vector, sort by that distance, and keep the first few rows.
SELECT id, content, embedding <-> '[3,1,2]' AS l2_distance
FROM items
ORDER BY embedding <-> '[3,1,2]'
LIMIT 5;The three parts do different jobs:
embedding <-> '[3,1,2]'is the L2 (Euclidean) distance between the stored vector and the query vector.ORDER BYranks rows from smallest distance to largest. Smaller always means closer, for every pgvector distance operator.LIMIT 5keeps the top five. The number you pass is often called k in "k nearest neighbors".
With no vector index on the table, PostgreSQL has no shortcut. It reads every row, computes the distance for each, and keeps the best k. Because every row is compared, the result is exact: no closer row can be missing.
What the planner does
You can check this with EXPLAIN. For a table without a vector index, the plan has this shape. The costs and row counts will differ on your system.
Limit
-> Sort
Sort Key: ((embedding <-> '[3,1,2]'::vector))
-> Seq Scan on itemsFor small LIMIT values PostgreSQL uses a top-N heapsort. It keeps only the k best rows in memory instead of sorting the whole table. Work grows linearly with the number of rows and with the vector dimension, since each distance touches every component.
Correction: the diagram must use the required fence format. Here it is in the proper place below.
Results for the sample data
For the query vector [3,1,2], the L2 distances are:
| id | content | vector | L2 distance |
|---|---|---|---|
| 3 | c | [1,1,1] | about 2.236 |
| 1 | a | [1,2,3] | about 2.449 |
| 2 | b | [4,5,6] | about 5.745 |
The order is c, a, b. The next section shows that this order changes with the operator.
Choosing the operator changes the ranking
The same query with cosine distance uses <=>. Cosine distance is 1 minus cosine similarity, so subtracting it from 1 gives a similarity score.
SELECT id, content, 1 - (embedding <=> '[3,1,2]') AS cosine_similarity
FROM items
ORDER BY embedding <=> '[3,1,2]'
LIMIT 5;Cosine compares direction and ignores length. For the sample rows it gives c (similarity about 0.926), then b (about 0.883), then a (about 0.786). Row b moves from last under L2 to second, because its direction is close to the query even though it is far away in space.
Inner product uses <#>, which returns the negative inner product. PostgreSQL index scans only support ascending order, so pgvector negates the value to make "larger product" sort first. For the sample rows the products are 11 for a, 29 for b and 6 for c. <#> returns -11, -29 and -6, so the order is b, a, c. Multiply by -1 if you want to display the positive product:
SELECT id, content, (embedding <#> '[3,1,2]') * -1 AS inner_product
FROM items
ORDER BY embedding <#> '[3,1,2]'
LIMIT 5;<+> is L1 (taxicab) distance and follows the same pattern.
| Operator | Metric | Sort direction in `ORDER BY` |
|---|---|---|
| `<->` | L2 distance | ascending |
| `<=>` | cosine distance | ascending |
| `<#>` | negative inner product | ascending |
| `<+>` | L1 distance | ascending |
Pick the operator that matches how your embedding model was trained or normalized. When vectors are normalized to length 1, cosine and inner product give the same ranking, and <#> can be slightly cheaper to compute.
Writing the query so it stays index-friendly
This chapter's queries are exact because no index exists. Later chapters add approximate indexes. The query shape you write now is the shape those indexes need, so build good habits early.
- Order by the bare distance expression, with the column on the left and the query vector on the right:
ORDER BY embedding <=> '[3,1,2]'. - Always include
LIMIT. An index can only help return the first k rows. WithoutLIMIT, PostgreSQL has to sort everything. - Order ascending. Do not add
DESC, and do not wrap the distance in other arithmetic insideORDER BY. - Select the computed distance separately in the
SELECTlist when you need to show it. TheORDER BYexpression stays plain.
A frequent mistake is to filter by distance, as in WHERE embedding <-> '[3,1,2]' < 3. This is valid SQL and gives correct results, but a vector index cannot serve it, so the database scans the whole table. For a range-style search, keep the ORDER BY ... LIMIT form and apply the threshold to its output:
SELECT id, content, dist
FROM (
SELECT id, content, embedding <-> '[3,1,2]' AS dist
FROM items
ORDER BY embedding <-> '[3,1,2]'
LIMIT 20
) AS nearest
WHERE dist < 3;The inner query returns at most 20 rows, and the outer query drops the ones that are too far away.
Common errors
- Dimension mismatch. The query vector must have the same number of dimensions as the column.
'[1,2]'against avector(3)column raises an error saying the vectors have different dimensions. - Unknown parameter type. In a prepared statement, a bare parameter may not be resolved as a vector. Add a cast:
ORDER BY embedding <=> $1::vector. - Zero vectors and cosine. A vector of all zeros has no direction, so its cosine distance is undefined and returns NaN. Avoid storing zero vectors in a column you search by cosine.
- NULL embeddings. The distance to a NULL vector is NULL. PostgreSQL sorts NULLs last in ascending order, so they only appear if fewer than k non-NULL rows exist. Filter them out with
WHERE embedding IS NOT NULLif that matters. - Ties. Rows at equal distance come back in no guaranteed order. Add a tie-breaker such as
, idwhen you need repeatable output.
SELECT id, content
FROM items
WHERE embedding IS NOT NULL
ORDER BY embedding <=> '[3,1,2]', id
LIMIT 5;When exact search is enough
Exact search needs no tuning and gives perfect recall. It suits tables of up to tens of thousands of rows, and queries that must return the true nearest rows. It is also the baseline you compare approximate indexes against when you measure recall. As the table grows, the full scan makes each query slower, which is the reason approximate indexes exist.
Exercise
Using the sample table and the query vector '[3,1,2]', which row is closest by inner product (<#>), and why does the query order by the <#> value ascending even though a larger inner product means a closer match?
Show answer
Row b is closest. Its inner product with the query is 29, the largest of the three (a gives 11, c gives 6). The <#> operator returns the negative inner product (-29, -11, -6), so an ascending sort puts b first. pgvector negates the value because index scans only support ascending order, so "smallest value first" has to mean "closest first" for every operator.
Exercise
Why does this query scan the whole table even after you add a vector index: SELECT id FROM items WHERE embedding <-> '[3,1,2]' < 3; How would you rewrite it to allow index use?
Show answer
The distance appears in a WHERE condition, not in ORDER BY ... LIMIT, and a vector index only supports ordered nearest-neighbor retrieval. Rewrite it as a subquery that does ORDER BY embedding <-> '[3,1,2]' LIMIT k, then apply the distance threshold in the outer query's WHERE clause.