Database / pgvector basics Interview Questions
What distance operators does pgvector provide and when do you use each?
pgvector defines several SQL operators for computing distance or similarity between vectors. The operator you choose affects both the mathematical semantics and which index types can accelerate the query.
| Operator | Name | Formula | Best for |
|---|---|---|---|
| <-> | L2 (Euclidean) distance | sqrt(sum((a-b)^2)) | General purpose; when vector magnitude carries meaning |
| <#> | Negative inner product | -sum(a*b) | Recommendation systems; normalised vectors |
| <=> | Cosine distance | 1 - (a.b / |a||b|) | Text embeddings; magnitude-independent similarity |
| <+> | L1 (Manhattan) distance | sum(|a-b|) | Robust to outliers; sparse-ish vectors |
| <~> | Hamming distance | Count of differing bits | Binary vectors (bit type only) |
| <%> | Jaccard distance | 1 - |A intersect B| / |A union B| | Binary vectors; set-like similarity |
-- L2 distance: find 5 nearest neighbours to '[3,1,2]' SELECT id, content, embedding <-> '[3,1,2]' AS distance FROM documents ORDER BY distance LIMIT 5; -- Cosine distance: best for text embeddings SELECT id, content, embedding <=> '[3,1,2]' AS cosine_dist FROM documents ORDER BY cosine_dist LIMIT 5; -- Inner product: NOTE <#> returns NEGATIVE inner product -- Negate the result to get actual similarity score: SELECT id, -(embedding <#> '[3,1,2]') AS inner_product_sim FROM documents ORDER BY embedding <#> '[3,1,2]' -- ASC = most similar (most negative) LIMIT 5; -- Get actual distance value (not just ordering): SELECT id, embedding <-> '[3,1,2]' AS l2_dist, embedding <=> '[3,1,2]' AS cos_dist FROM documents LIMIT 10;
More Related questions...