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;
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
